Part Number Hot Search : 
123B3RC B90N6T MBR60 ADUM7234 05111 T2500B 1N629 T1143
Product Description
Full Text Search
 

To Download ATMEGA8535L-8AUR Datasheet File

  If you can't view the Datasheet, Please click here to try to view without PDF Reader .  
 
 


  Datasheet File OCR Text:
  features ? high-performance, low-power avr ? 8-bit microcontroller ? advanced risc architecture ? 130 powerful instructions ? most single clock cycle execution ? 32 x 8 general purpose working registers ? fully static operation ? up to 16 mips throughput at 16 mhz ? on-chip 2-cycle multiplier ? nonvolatile program and data memories ? 8k bytes of in-system self-programmable flash endurance: 10,000 write/erase cycles ? optional boot code section with independent lock bits in-system programming by on-chip boot program true read-while-w rite operation ? 512 bytes eeprom endurance: 100,000 write/erase cycles ? 512 bytes internal sram ? programming lock for software security ? peripheral features ? two 8-bit timer/counters with se parate prescalers and compare modes ? one 16-bit timer/counter with separate prescaler, compare mode, and capture mode ? real time counter with separate oscillator ? four pwm channels ? 8-channel, 10-bit adc 8 single-ended channels 7 differential channels for tqfp package only 2 differential channels with programmabl e gain at 1x, 10x, or 200x for tqfp package only ? byte-oriented two-wi re serial interface ? programmable serial usart ? master/slave spi serial interface ? programmable watchdog timer with separate on-chip oscillator ? on-chip analog comparator ? special microcontroller features ? power-on reset and programmable brown-out detection ? internal calibrated rc oscillator ? external and internal interrupt sources ? six sleep modes: idle, adc noise reduction, power-save, power-down, standby and extended standby ? i/o and packages ? 32 programmable i/o lines ? 40-pin pdip, 44-lead tqfp, 44 -lead plcc, and 44-pad qfn/mlf ? operating voltages ? 2.7 - 5.5v for atmega8535l ? 4.5 - 5.5v for atmega8535 ? speed grades ? 0 - 8 mhz for atmega8535l ? 0 - 16 mhz for atmega8535 8-bit microcontroller with 8k bytes in-system programmable flash atmega8535 atmega8535l 2502k?avr?10/06
2 atmega8535(l) 2502k?avr?10/06 pin configurations figure 1. pinout atmega8535 disclaimer typical values contained in this data sheet are based on simulations and characteriza- tion of other avr microcontrollers manufactured on the same process technology. min and max values will be available afte r the device is characterized. (xck/t0) pb0 (t1) pb1 (int2/ain0) pb2 (oc0/ain1) pb3 (ss) pb4 (mosi) pb5 (miso) pb6 (sck) pb7 reset vcc gnd xtal2 xtal1 (rxd) pd0 (txd) pd1 (int0) pd2 (int1) pd3 (oc1b) pd4 (oc1a) pd5 (icp1) pd6 pa0 (adc0) pa1 (adc1) pa2 (adc2) pa3 (adc3) pa4 (adc4) pa5 (adc5) pa6 (adc6) pa7 (adc7) aref gnd avcc pc7 (tosc2) pc6 (tosc1) pc5 pc4 pc3 pc2 pc1 (sda) pc0 (scl) pd7 (oc2) 1 2 3 4 5 6 7 8 9 10 11 33 32 31 30 29 28 27 26 25 24 23 (mosi) pb5 (miso) pb6 (sck) pb7 reset vcc gnd xtal2 xtal1 (rxd) pd0 (txd) pd1 (int0) pd2 pa4 (adc4) pa5 (adc5) pa6 (adc6) pa7 (adc7) aref gnd avcc pc7 (tosc2) pc6 (tosc1) pc5 pc4 44 43 42 41 40 39 38 37 36 35 34 12 13 14 15 16 17 18 19 20 21 22 (int1) pd3 (oc1b) pd4 (oc1a) pd5 (icp1) pd6 (oc2) pd7 vcc gnd (scl) pc0 (sda) pc1 pc2 pc3 pb4 (ss) pb3 (ain1/oc0) pb2 (ain0/int2) pb1 (t1) pb0 (xck/t0) gnd vcc pa0 (adc0) pa1 (adc1) pa2 (adc2) pa3 (adc3) 7 8 9 10 11 12 13 14 15 16 17 39 38 37 36 35 34 33 32 31 30 29 (mosi) pb5 (miso) pb6 (sck) pb7 reset vcc gnd xtal2 xtal1 (rxd) pd0 (txd) pd1 (int0) pd2 pa4 (adc4) pa5 (adc5) pa6 (adc6) pa7 (adc7) aref gnd avcc pc7 (tosc2) pc6 (tosc1) pc5 pc4 6 5 4 3 2 1 44 43 42 41 40 18 19 20 21 22 23 24 25 26 27 28 (int1) pd3 (oc1b) pd4 (oc1a) pd5 (icp1) pd6 (oc2) pd7 vcc gnd (scl) pc0 (sda) pc1 pc2 pc3 pb4 (ss) pb3 (ain1/oc0) pb2 (ain0/int2) pb1 (t1) pb0 (xck/t0) gnd vcc pa0 (adc0) pa1 (adc1) pa2 (adc2) pa3 (adc3) plcc note: mlf bottom pad should be soldered to ground.
3 atmega8535(l) 2502k?avr?10/06 overview the atmega8535 is a low-power cmos 8-bit microcontroller based on the avr enhanced risc architecture. by executing instructions in a single clock cycle, the atmega8535 achieves throughputs approaching 1 mips per mhz allowing the system designer to optimize power consum ption versus processing speed. block diagram figure 2. block diagram internal oscillator oscillator watchdog timer mcu ctrl. & timing oscillator timers/ counters interrupt unit stack pointer eeprom sram status register usart program counter program flash instruction register instruction decoder programming logic spi adc interface comp. interface porta drivers/buffers porta digital interface general purpose registers x y z alu + - portc drivers/buffers portc digital interface portb digital interface portb drivers/buffers portd digital interface portd drivers/buffers xtal1 xtal2 reset control lines v cc gnd mux & adc aref pa0 - pa7 pc0 - pc7 pd0 - pd7 pb0 - pb7 avr cpu twi avcc internal calibrated oscillator
4 atmega8535(l) 2502k?avr?10/06 the avr core combines a rich instruction se t with 32 general purpose working registers. all 32 registers are directly connected to the arithmetic logic unit (alu), allowing two independent registers to be accessed in one si ngle instruction executed in one clock cycle. the resulting architecture is more code efficient while achieving throughputs up to ten times faster than conventional cisc microcontrollers. the atmega8535 provides the following features: 8k bytes of in-system programmable flash with read-while-wri te capabilities, 512 byte s eeprom, 512 bytes sram, 32 general purpose i/o lines, 32 general purpose working registers, three flexible timer/counters with compare modes, internal and external interrupts, a serial program- mable usart, a byte oriented two-wire seri al interface, an 8-channel, 10-bit adc with optional differential input stage with programmable gain in tqfp package, a program- mable watchdog timer with internal oscilla tor, an spi serial port, and six software selectable power saving modes. the idle mode stops the cpu while allowing the sram, timer/counters, spi port, and interrupt system to continue functioning. the power-down mode saves the register contents but freezes the oscill ator, disabling all other chip functions until the next interrupt or hardware reset. in power-save mode, the asynchronous timer continues to run, allowi ng the user to maintain a timer base while the rest of the device is sleeping. the adc noise reduction mode stops the cpu and all i/o modules except asynchronous timer and adc, to minimize switching noise during adc conversions. in standby mode, the crysta l/resonator oscillator is running while the rest of the device is sleeping. this allows very fast start-up co mbined with low-power consumption. in extended standby mode, both the main oscillator and the asynchro- nous timer continue to run. the device is manufactured using atmel?s hi gh density nonvolatile memory technology. the on-chip isp flash allows the program memory to be reprogrammed in-system through an spi serial interface, by a conventional nonvolatile memory programmer, or by an on-chip boot program running on the avr core. the boot program can use any interface to download the application program in the application flash memory. soft- ware in the boot flas h section will continue to run while the application flash section is updated, providing true read-while-write operation. by combining an 8-bit risc cpu with in-system self-programmable flash on a monolithic chip, the atmel atmega8535 is a powerful microcontroller that provides a highly flexible and cost effective solution to many embedded control applications. the atmega8535 avr is supported with a full suite of program and system develop- ment tools including: c compilers, macro assemblers, program debugger/simulators, in- circuit emulators, and evaluation kits. at90s8535 compatibility the atmega8535 provides all the features of the at90s8535. in addition, several new features are added. the atmega8535 is backward compatible with at90s8535 in most cases. however, some incompatibilities between the two microcontrollers exist. to solve this problem, an at 90s8535 compatibility mode can be select ed by programming the s8535c fuse. atmega8535 is pin compatible with at90s8535, and can replace the at90s8535 on current printed circuit boards. however, the location of fuse bits and the electrical characteristics differs between the two devices. at90s8535 compatibility mode programming the s8535c fuse will ch ange the following functionality: ? the timed sequence for changing the watchdog time-out period is disabled. see ?timed sequences for changing the configuration of the watchdog timer? on page 45 for details. ? the double buffering of the usart receive register is disabled. see ?avr usart vs. avr uart ? compatibility? on page 146 for details.
5 atmega8535(l) 2502k?avr?10/06 pin descriptions v cc digital supply voltage. gnd ground. port a (pa7..pa0) port a serves as the analog inputs to the a/d converter. port a also serves as an 8-bit bi-directional i/o port, if the a/d converter is not used. port pins can provide internal pull-up resistors (selected for each bit). the port a output buffers have symmetrical drive characteristics with both high sink and source capability. when pins pa0 to pa7 are used as inputs a nd are externally pulled low, they will source current if the internal pull-up resistors are activated. the port a pins are tri-stated when a reset condition becomes active, even if the clock is not running. port b (pb7..pb0) port b is an 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port b output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port b pi ns that are externally pulled low will source current if the pull-up resistors are activated. the port b pins are tri-stated when a reset condition becomes active, even if the clock is not running. port b also serves the functions of various special features of the atmega8535 as listed on page 60. port c (pc7..pc0) port c is an 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port c output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port c pi ns that are externally pulled low will source current if the pull-up resistors are activated. the port c pins are tri-stated when a reset condition becomes active, even if the clock is not running. port d (pd7..pd0) port d is an 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port d output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port d pi ns that are externally pulled low will source current if the pull-up resistors are activated. the port d pins are tri-stated when a reset condition becomes active, even if the clock is not running. port d also serves the functions of various special features of the atmega8535 as listed on page 64. reset reset input. a low level on this pin for longer than the minimu m pulse length will gener- ate a reset, even if the clock is not running. the minimum pulse length is given in table 15 on page 37. shorter pulses are not guaranteed to generate a reset. xtal1 input to the inverting oscillato r amplifier and input to the in ternal clock operating circuit. xtal2 output from the invert ing oscillator amplifier. avcc avcc is the supply voltage pin for port a and the a/d converter. it should be externally connected to v cc , even if the adc is not used. if the adc is used, it should be con- nected to v cc through a low-pass filter. aref aref is the analog reference pin for the a/d converter.
6 atmega8535(l) 2502k?avr?10/06 resources a comprehensive set of development tools, application notes and datasheets are avail- able for download on http://www.atmel.com/avr.
7 atmega8535(l) 2502k?avr?10/06 about code examples this documentation contains simple code examples that briefly show how to use various parts of the device. these code examples assume that the part specific header file is included before compilation. be aware that not all c compiler vendors include bit defini- tions in the header files and interrupt handling in c is compiler dependent. please confirm with the c compiler documentation for more details.
8 atmega8535(l) 2502k?avr?10/06 avr cpu core introduction this section discusses the avr core archit ecture in general. the main function of the cpu core is to ensure correct program execution. the cpu must therefore be able to access memories, perform calculations, control peripherals, and handle interrupts. architectural overview figure 3. block diagram of the avr mcu architecture in order to maximize performance and para llelism, the avr uses a harvard architecture ? with separate memories and buses for program and data. instructions in the program memory are executed with a single level pipel ining. while one instruction is being exe- cuted, the next instruction is pre-fetched from the program memory. this concept enables instructions to be executed in every clock cycle. the program memory is in- system re-programmable flash memory. the fast-access register file contains 32 x 8-bit general purpose working registers with a single clock cycle access time. this allows single-cycle arithmetic logic unit (alu) operation. in a typical alu operation, two operands are output from the register file, the operation is executed, and the result is stored back in the register file ? in one clock cycle. flash program memory instruction register instruction decoder program counter control lines 32 x 8 general purpose registrers alu status and control i/o lines eeprom 8-bit data bus data sram direct addressing indirect addressing interrupt unit spi unit watchdog timer analog comparator i/o module 2 i/o module1 i/o module n
9 atmega8535(l) 2502k?avr?10/06 six of the 32 registers can be used as three 16-bit indirect address register pointers for data space addressing ? enabling efficient address calculations. one of the these address pointers can also be used as an addr ess pointer for look up tables in flash pro- gram memory. these added function registers are the 16-bit x-, y-, and z-registers, described later in this section. the alu supports arithmetic and logic operations between registers or between a con- stant and a register. single register operations can also be executed in the alu. after an arithmetic operation, the status register is updated to reflect information about the result of the operation. program flow is provided by conditional and unconditional jump and call instructions, able to directly address the whole address s pace. most avr instructions have a single 16-bit word format. every program memory address contains a 16- or 32-bit instruction. program flash memory space is divided in two sections, the boot program section and the application program section. both sections have dedicated lock bits for write and read/write protection. the spm instruction that writes into the application flash memory section must reside in the boot program section. during interrupts and subroutine calls, the return address program counter (pc) is stored on the stack. the stack is effectively allocated in the general data sram, and consequently the stack size is only limited by the total sram size and the usage of the sram. all user programs must initialize the sp in the reset routine (before subroutines or interrupts are executed). the stack pointer sp is read/write accessible in the i/o space. the data sram can easily be accessed through the five different addressing modes supported in the avr architecture. the memory spaces in the avr architecture are all linear and regular memory maps. a flexible interrupt module has its control registers in the i/o space with an additional global interrupt enable bit in the status register. all interrupts have a separate interrupt vector in the interrupt vector table. the interrupts have priority in accordance with their interrupt vector position. the lower the interrupt vector address, the higher the priority. the i/o memory space contains 64 addresse s for cpu peripheral functions as control registers, spi, and other i/o functions. the i/o memory can be accessed directly, or as the data space locations following those of the register file, 0x20 - 0x5f. alu ? arithmetic logic unit the high-performance avr alu operates in direct connection with all the 32 general purpose working registers. within a single clock cycle, arithmetic operations between general purpose registers or between a register and an immediate are executed. the alu operations are divided into three main categories ? arithmetic, logical, and bit-func- tions. some implementations of the architecture also provide a powerful multiplier supporting both signed/unsigned multiplication and fractional format. see the ?instruc- tion set? section for a detailed description.
10 atmega8535(l) 2502k?avr?10/06 status register the status register contains information about the result of the most recently executed arithmetic instruction. this information can be used for altering program flow in order to perform conditional operations. note that the status register is updated after all alu operations, as specified in the instruction set reference. this will, in many cases, remove the need for using the dedicated compare instructions, resulting in faster and more compact code. the status register is not automatically stored when entering an interrupt routine and restored when returning from an interrupt. this must be handled by software. the avr status register ? sreg ? is defined as: ? bit 7 ? i: global interrupt enable the global interrupt enable bit must be set for the interrupts to be enabled. the individ- ual interrupt enable control is then performed in separate control registers. if the global interrupt enable register is cleared, n one of the interrupts are enabled independent of the individual interrupt enable settings. the i-bit is cleared by hardware after an interrupt has occurred, and is set by the reti instruction to enable subsequent interrupts. the i- bit can also be set and cleared by the application with the sei and cli instructions, as described in the instruction set reference. ? bit 6 ? t: bit copy storage the bit copy instructions bld (bit load) and bst (bit store) use the t-bit as source or destination for the operated bit. a bit from a register in the register file can be copied into t by the bst instruction, and a bit in t can be copied into a bit in a register in the register file by the bld instruction. ? bit 5 ? h: half carry flag the half carry flag h indicate s a half carry in some arithm etic operations. half carry is useful in bcd arithmetic. see the ?instruction set description? for detailed information. ? bit 4 ? s: sign bit, s = n v the s-bit is always an exclusive or between the negative flag n and the two?s comple- ment overflow flag v. see the ?instruction set description? for detailed information. ? bit 3 ? v: two?s complement overflow flag the two?s complement overflow flag v supports two?s complement arithmetics. see the ?instruction set description? for detailed information. ? bit 2 ? n: negative flag the negative flag n indicates a negative result in an arithmetic or logic operation. see the ?instruction set description? for detailed information. ? bit 1 ? z: zero flag the zero flag z indicates a zero result in an arithmetic or logic operation. see the ?instruction set description? for detailed information. ? bit 0 ? c: carry flag the carry flag c indicates a carry in an arit hmetic or logic operation. see the ?instruc- tion set description? for detailed information. bit 76543210 i t h s v n z c sreg read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
11 atmega8535(l) 2502k?avr?10/06 general purpose register file the register file is optimized for the avr enhanced risc instruction set. in order to achieve the required performance and flexib ility, the following inpu t/output schemes are supported by the register file: ? one 8-bit output operand and one 8-bit result input ? two 8-bit output operands and one 8-bit result input ? two 8-bit output operands and one 16-bit result input ? one 16-bit output operand and one 16-bit result input figure 4 shows the structure of the 32 general purpose working registers in the cpu. figure 4. avr cpu general purpose working registers most of the instructions operating on the register file have direct access to all registers, and most of them are single cycle instructions. as shown in figure 4, each register is also assigned a data memory address, mapping them directly into the first 32 locations of the user data space. although not being phys- ically implemented as sram locations, this memory organization provides great flexibility in access of the registers, as th e x-, y-, and z-pointer registers can be set to index any register in the file. 7 0 addr. r0 0x00 r1 0x01 r2 0x02 ? r13 0x0d general r14 0x0e purpose r15 0x0f working r16 0x10 registers r17 0x11 ? r26 0x1a x-register low byte r27 0x1b x-register high byte r28 0x1c y-register low byte r29 0x1d y-register high byte r30 0x1e z-register low byte r31 0x1f z-register high byte
12 atmega8535(l) 2502k?avr?10/06 the x-register, y-register, and z-register the registers r26..r31 have some added f unctions to their general purpose usage. these registers are 16-bit address pointers for indirect addressing of the data space. the three indirect address registers x, y, and z are defined as described in figure 5. figure 5. the x-, y-, and z-registers in the different addressing modes, these address registers have functions as fixed dis- placement, automatic increment, and automatic decrement (see the instruction set reference for details). stack pointer the stack is mainly used for storing temporary data, for storing local variables and for storing return addresses after interrupts and subroutine calls. the stack pointer regis- ter always points to the top of the stack. note that the stack is implemented as growing from higher memory locations to lower memory locations. this implies that a stack push command decreases the stack pointer. the stack pointer points to the data sram stack area where the subroutine and inter- rupt stacks are located. this stack space in the data sram must be defined by the program before any subroutine calls are executed or interrupts are enabled. the stack pointer must be set to point above 0x60. the stack pointer is decremented by one when data is pushed onto the stack with the push instruction, and it is decremented by two when the return address is pushed onto the stack with subroutine call or interrupt. the stack pointer is incremented by one when data is popped from the stack with the pop instruction, and it is incremented by two when data is popped from the stack with return from subroutine ret or return from interrupt reti. the avr stack pointer is implemented as two 8-bit registers in the i/o space. the num- ber of bits actually used is implementation dependent. note that the data space in some implementations of the avr architecture is so small that only spl is needed. in this case, the sph register will not be present. 15 xh xl 0 x-register 7 0 7 0 r27 (0x1b) r26 (0x1a) 15 yh yl 0 y-register 7 0 7 0 r29 (0x1d) r28 (0x1c) 15 zh zl 0 z-register 7 0 7 0 r31 (0x1f) r30 (0x1e) bit 151413121110 9 8 - - - - - - sp9 sp8 sph sp7 sp6 sp5 sp4 sp3 sp2 sp1 sp0 spl 76543210 read/write r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 00000000
13 atmega8535(l) 2502k?avr?10/06 instruction execution timing this section describes the general access timing concepts for instruction execution. the avr cpu is driven by the cpu clock clk cpu , directly generated from the selected clock source for the chip. no intern al clock division is used. figure 6 shows the parallel instruction fetches and instruction executions enabled by the harvard architecture and the fast-access register file concept. this is the basic pipelin- ing concept to obtain up to 1 mips per mhz with the corresponding unique results for functions per cost, functions per clocks, and functions per power-unit. figure 6. the parallel instruction fetches and instruction executions figure 7 shows the internal timing concept for the register file. in a single clock cycle an alu operation using two register operands is executed, and the result is stored back to the destination register. figure 7. single cycle alu operation reset and interrupt handling the avr provides several different interrupt sources. these interrupts and the separate reset vector each have a separate program vector in the program memory space. all interrupts are assigned individual enable bits which must be written logic one together with the global interrupt enable bit in the status register in order to enable the interrupt. depending on the program counter value, in terrupts may be automatically disabled when boot lock bits blb02 or blb12 are programmed. this feature improves software security. see the section ?memory programming? on page 237 for details. the lowest addresses in the program memory space are, by default, defined as the reset and interrupt vectors. the complete list of vectors is shown in ?interrupts? on page 46. the list also determines the priority levels of the different interrupts. the lower the address, the higher the priority level is. reset has the highest priority, and next is int0 ? the external interrupt request 0. the interrupt vectors can be moved to the start of the boot flash section by setting the ivsel bit in the ge neral interrupt control regis- ter (gicr). refer to ?interrupts? on page 46 for more information. the reset vector can clk 1st instruction fetch 1st instruction execute 2nd instruction fetch 2nd instruction execute 3rd instruction fetch 3rd instruction execute 4th instruction fetch t1 t2 t3 t4 cpu total execution time register operands fetch alu operation execute result write back t1 t2 t3 t4 clk cpu
14 atmega8535(l) 2502k?avr?10/06 also be moved to the start of the boot flash section by programming the bootrst fuse, see ?boot loader support ? read-while-write self-programming? on page 224. when an interrupt occurs, the global interrupt enable i-bit is cleared and all interrupts are disabled. the user software can write logic one to the i-bit to enable nested inter- rupts. all enabled interrupts can then interrupt the current interrupt routine. the i-bit is automatically set when a return from interrupt instruction ? reti ? is executed. there are basically two types of interrupts. the first type is triggered by an event that sets the interrupt flag. for these interrupts, the program counter is vectored to the actual interrupt vector in order to execute the interrupt handling routine, and hardware clears the corresponding interrupt flag. interr upt flags can also be cleared by writing a logic one to the flag bit position(s) to be cleared. if an interrupt condition occurs while the corresponding interrupt enable bit is cleared, the interrupt flag will be set and remem- bered until the interrupt is enabled, or the flag is cleared by software. similarly, if one or more interrupt conditions occur while the global interrupt enable bit is cleared, the cor- responding interrupt fl ag(s) will be set and remembered until the global interrupt enable bit is set, and will then be exec uted by order of priority. the second type of interrupts will trigger as long as the interrupt condition is present. these interrupts do not necessarily have interrup t flags. if the interrupt condition disap- pears before the interrupt is enabled , the interrupt will not be triggered. when the avr exits from an in terrupt, it will always return to the main pr ogram and exe- cute one more instruction before any pending interrupt is served. note that the status register is not automatically stored when entering an interrupt rou- tine, nor restored when returning from an interrupt routine. this must be handled by software. when using the cli instruction to disable in terrupts, the interrupts will be immediately disabled. no interrupt will be exec uted after the cli instruction, even if it occurs simulta- neously with the cli instruction. the following example shows how this can be used to avoid interrupts during the timed eeprom write sequence. assembly code example in r16, sreg ; store sreg value cli ; disable interrupts during timed sequence sbi eecr, eemwe ; start eeprom write sbi eecr, eewe out sreg, r16 ; restore sreg value (i-bit) c code example char csreg; csreg = sreg; /* store sreg value */ /* disable interrupts during timed sequence */ _cli(); eecr |= (1< 15 atmega8535(l) 2502k?avr?10/06 when using the sei instructio n to enable interrupts, the in struction following sei will be executed before any pending interrupts, as shown in this example. interrupt response time the interrupt execution response for all the enabled avr interrupts is four clock cycles minimum. after four clock cycles, the program vector address for the actual interrupt handling routine is executed. during this four clock cycle period, the program counter is pushed onto the stack. the vector is normally a jump to the interrupt routine, and this jump takes three clock cycles. if an interr upt occurs during execution of a multi-cycle instruction, this instruction is completed before the interrupt is served. if an interrupt occurs when the mcu is in sleep mode, the interrupt execution response time is increased by four clock cycles. this increase comes in addition to the start-up time from the selected sleep mode. a return from an interrupt handling routine ta kes four clock cycles. during these four clock cycles, the program counter (two bytes) is popped back from the stack, the stack pointer is incremented by two, and the i-bit in sreg is set. assembly code example sei ; set global interrupt enable sleep ; enter sleep, waiting for interrupt ; note: will enter sleep before any pending ; interrupt(s) c code example _sei(); /* set global interrupt enable */ _sleep(); /* enter sleep, waiting for interrupt */ /* note: will enter sleep before any pending interrupt(s) */
16 atmega8535(l) 2502k?avr?10/06 avr atmega8535 memories this section describes the different memories in the atmega8535. the avr architec- ture has two main memory spaces, the data memory and the program memory space. in addition, the atmega8535 features an eeprom memory for data storage. all three memory spaces are linear and regular. in-system reprogrammable flash program memory the atmega8535 contains 8k bytes on-chi p in-system reprogrammable flash mem- ory for program storage. since all avr instructions are 16 or 32 bits wide, the flash is organized as 4k x 16. for software security, the flash program memory space is divided into two sections, boot program section and application program section. the flash memory has an endurance of at least 10,000 write/erase cycles. the atmega8535 program counter (pc) is 12 bits wide, thus addressing the 4k program memory locations. the operation of boot program section and associated boot lock bits for software protection are described in detail in ?boot loader support ? read- while-write self-programming? on page 224. ?memory programming? on page 237 con- tains a detailed description on flash programming in spi or parallel programming mode. constant tables can be allocated within th e entire program memory address space (see the lpm ? load program memory instruction description). timing diagrams for instruction fetch and exec ution are presented in ?instruction execu- tion timing? on page 13. figure 8. program memory map $000 $fff application flash section boot flash section
17 atmega8535(l) 2502k?avr?10/06 sram data memory figure 9 shows how the atmega8535 sram memory is organized. the 608 data memory locations address the register file, the i/o memory, and the internal data sram. the first 96 locations address the register file and i/o memory, and the next 512 locations address the internal data sram. the five different addressing modes for the data memory cover: direct, indirect with dis- placement, indirect, indirect with pre-decrement, and indirect with post-increment. in the register file, registers r26 to r31 feature the indirect addressing pointer registers. the direct addressing reaches the entire data space. the indirect with displacement mode reaches 63 address locations from the base address given by the y- or z-register. when using register indirect addressing modes with automatic pre-decrement and post- increment, the address registers x, y, and z are decremented or incremented. the 32 general purpose working registers, 64 i/o registers, and the 512 bytes of inter- nal data sram in the atmega8535 are all accessible through all these addressing modes. the register file is described in ?general purpose register file? on page 11. figure 9. data memory map register file r0 r1 r2 r29 r30 r31 i/o registers $00 $01 $02 ... $3d $3e $3f ... $0000 $0001 $0002 $001d $001e $001f $0020 $0021 $0022 ... $005d $005e $005f ... data address space $0060 $0061 $025e $025f ... internal sram
18 atmega8535(l) 2502k?avr?10/06 data memory access times this section describes the general access ti ming concepts for internal memory access. the internal data sram access is performed in two clk cpu cycles as described in figure 10. figure 10. on-chip data sram access cycles eeprom data memory the atmega8535 co ntains 512 bytes of data eeprom memory. it is organized as a separate data space, in which single bytes can be read and written. the eeprom has an endurance of at least 100,000 write/erase cycles. the access between the eeprom and the cpu is described in the following, specifying the eeprom address registers, the eeprom data register, and the eeprom control register. ?memory programming? on page 237 contains a detailed description on eeprom pro- gramming in spi or parallel programming mode. eeprom read/write access the eeprom access registers are accessible in the i/o space. the write access time for the eeprom is given in table 1. a self-timing function, how- ever, lets the user software detect when t he next byte can be written. if the user code contains instructions that write the eepr om, some precautions must be taken. in heavily filtered power supplies, v cc is likely to rise or fall slowly on power-up/down. this causes the device, for some period of time, to run at a voltage lower than specified as minimum for the clock frequency used, see ?preventing eeprom corruption? on page 22 for details on how to avoid problems in these situations. in order to prevent unintentional eeprom writes, a specific write procedure must be fol- lowed. refer to the descripti on of the eeprom control regi ster for details on this. when the eeprom is read, the cpu is halt ed for four clock cycles before the next instruction is executed. when the eeprom is written, the cpu is halted for two clock cycles before the next instruction is executed. clk wr rd data data address address valid t1 t2 t3 compute address read write cpu memory access instruction next instruction
19 atmega8535(l) 2502k?avr?10/06 the eeprom address register ? eearh and eearl ? bits 15..9 ? res: reserved bits these bits are reserved bits in the atmega8535 and will always read as zero. ? bits 8..0 ? eear8..0: eeprom address the eeprom address registers ? eearh and eearl specify t he eeprom address in the 512 bytes eeprom space. the ee prom data bytes are addressed linearly between 0 and 511. the initial value of eear is undefined. a proper value must be writ- ten before the eeprom may be accessed. the eeprom data register ? eedr ? bits 7..0 ? eedr7..0: eeprom data for the eeprom write operation, the eedr register contains the data to be written to the eeprom in the address gi ven by the eear register. for the eeprom read oper- ation, the eedr contains the data read out from the eeprom at the address given by eear. the eeprom control register ? eecr ? bits 7..4 ? res: reserved bits these bits are reserved bits in the atmega8535 and will always read as zero. ? bit 3 ? eerie: eeprom ready interrupt enable writing eerie to one enables the eeprom ready interrupt if the i-bit in sreg is set. writing eerie to zero disables the interrupt. the eeprom ready interrupt generates a constant interrupt when eewe is cleared. ? bit 2 ? eemwe: eeprom master write enable the eemwe bit determines w hether setting eewe to one causes the eeprom to be written. when eemwe is set, setting eewe wit hin four clock cycles will write data to the eeprom at the selected address if eemwe is zero, setting eewe will have no effect. when eemwe has been written to one by software, hardware clears the bit to zero after four clock cycles. see the description of the eewe bit for an eeprom write procedure. ? bit 1 ? eewe: eeprom write enable the eeprom write enable signal eewe is the write strobe to the eeprom. when address and data are correctly set up, the eewe bit must be written to one to write the bit 151413121110 9 8 ???????eear8eearh eear7 eear6 eear5 eear4 eear3 eear2 eear1 eear0 eearl 76543210 read/writerrrrrrrr/w r/w r/w r/w r/w r/w r/w r/w r/w initial value0000000x xxxxxxxx bit 76543210 msb lsb eedr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ????eerieeemweeeweeereeecr read/write r r r r r/w r/w r/w r/w initial value000000x0
20 atmega8535(l) 2502k?avr?10/06 value into the eeprom. the eemwe bit must be written to one bef ore a logical one is written to eewe, otherwise no eeprom wr ite takes place. th e following procedure should be followed when writing the eeprom (the order of steps 3 and 4 is not essential): 1. wait until eewe becomes zero. 2. wait until spmen in spmcr becomes zero. 3. write new eeprom addr ess to eear (optional). 4. write new eeprom data to eedr (optional). 5. write a logical one to the eemwe bit while writing a zero to eewe in eecr. 6. within four clock cycles after setting eemwe, write a logical one to eewe. the eeprom can not be programmed during a cpu write to the flash memory. the software must check that the flash programming is completed before initiating a new eeprom write. step 2 is only relevant if the software contains a boot loader allowing the cpu to program the flash. if the flash is never updated by the cpu, step 2 can be omitted. see ?boot loader support ? read-while-write self-programming? on page 224 for details about boot programming. caution: an interrupt be tween step 5 and step 6 will make the write cycle fail, since the eeprom master write enable will time-out. if an interrupt routine accessing the eeprom is interrupting an other eeprom access , the eear or eedr register will be modified, causing the interrupted eeprom ac cess to fail. it is recommended to have the global interrupt flag cleared during all the steps to avoid these problems. when the write access time has elapsed, the eewe bit is cleared by hardware. the user software can poll this bit and wait for a zero before writing the next byte. when eewe has been set, the cpu is halted for tw o cycles before the next instruction is executed. ? bit 0 ? eere: eeprom read enable the eeprom read enable signal eere is the read st robe to the eeprom. when the correct address is set up in the eear regist er, the eere bit must be written to a logic one to trigger the eeprom re ad. the eeprom read access takes one instruction, and the requested data is availabl e immediately. when the ee prom is read, the cpu is halted for four cycles before the next instruction is executed. the user should poll the eewe bit before starting the read operation. if a write operation is in progress, it is neither possible to read the eeprom, nor to change the eear register. the calibrated oscillator is us ed to time the eeprom access es. table 1 lists the typical programming time for eeprom access from the cpu. note: 1. uses 1 mhz clock, independent of cksel fuse settings. table 1. eeprom programming time symbol number of calibrated rc oscillator cycles (1) typ programming time eeprom write (from cpu) 8448 8.4 ms
21 atmega8535(l) 2502k?avr?10/06 the following code examples show one assemb ly and one c function for writing to the eeprom. the examples assume that interrupts are controlled (e.g., by disabling inter- rupts globally) so that no inte rrupts will occur during execut ion of these functions. the examples also assume that no flash boot loader is present in the software. if such code is present, the eeprom write function must also wait for any ongoing spm com- mand to finish. assembly code example eeprom_write: ; wait for completion of previous write sbic eecr,eewe rjmp eeprom_write ; set up address (r18:r17) in address register out eearh, r18 out eearl, r17 ; write data (r16) to data register out eedr,r16 ; write logical one to eemwe sbi eecr,eemwe ; start eeprom write by setting eewe sbi eecr,eewe ret c code example void eeprom_write( unsigned int uiaddress, unsigned char ucdata) { /* wait for completion of previous write */ while(eecr & (1< 22 atmega8535(l) 2502k?avr?10/06 the next code examples show assembly an d c functions for reading the eeprom. the examples assume that interr upts are controlled so that no interrupts will occur during execution of these functions. eeprom write during power- down sleep mode when entering power-down sl eep mode while an eeprom writ e operation is active, the eeprom write operation will cont inue, and will complete before the write access time has passed. however, when t he write operation is complete d, the oscillator continues running, and as a consequence, the device does not enter power-down entirely. it is therefore recommen ded to verify that the eeprom wr ite operation is completed before entering power-down. preventing eeprom corruption during periods of low v cc , the eeprom data can be corrup ted because the supply volt- age is too low for the cpu and the eeprom to operate prope rly. these issues are the same as for board le vel systems using eeprom and th e same design solutions should be applied. an eeprom data corruption can be caused by two situations when the voltage is too low. first, a regular write sequence to the eeprom requires a minimum voltage to operate correctly. secondly, the cpu itself ca n execute instructions incorrectly, if the supply voltage is too low. assembly code example eeprom_read: ; wait for completion of previous write sbic eecr,eewe rjmp eeprom_read ; set up address (r18:r17) in address register out eearh, r18 out eearl, r17 ; start eeprom read by writing eere sbi eecr,eere ; read data from data register in r16,eedr ret c code example unsigned char eeprom_read( unsigned int uiaddress) { /* wait for completion of previous write */ while(eecr & (1< 23 atmega8535(l) 2502k?avr?10/06 eeprom data corruption can easily be avoided by following this design recommendation: keep the avr reset active (low) during perio ds of insufficient power supply volt- age. this can be done by enabling the internal brown-out detector (bod). if the detection level of the internal bod does not match the needed detection level, an external low v cc reset protection circuit can be used. if a reset occurs while a write operation is in progress, the write operation will be completed provided that the power supply voltage is sufficient. i/o memory the i/o space definition of the atmega8535 is shown in page 299. all atmega8535 i/os and peripherals are placed in the i/o space. the i/o locations are accessed by the in and out instructions, transferring data between the 32 general pur- pose working registers and the i/o space. i/o registers within the address range 0x00 - 0x1f are directly bit-accessible using the sbi and cbi instructions. in these registers, the value of single bits can be checked by using the sbis and sbic instructions. refer to the instruction set section for more details. when using the i/o specific commands in and out, the i/o addresses 0x00 - 0x3f must be used. when addressing i/o registers as data space using ld and st instructions , 0x20 must be added to these addresses. for compatibility with futu re devices, reserved bits should be written to ze ro if accessed. reserved i/o memory addresses should never be written. some of the status flags are cleared by writing a logical one to them. note that the cbi and sbi instructions will operate on all bits in the i/o register, writing a one back into any flag read as set, thus clearing the flag. the cbi and sbi instructions work with reg- isters 0x00 to 0x1f only. the i/o and peripherals control registers are explained in later sections.
24 atmega8535(l) 2502k?avr?10/06 system clock and clock options clock systems and their distribution figure 11 presents the principal clock system s in the avr and their distribution. all of the clocks need not be active at a given time. in order to reduce power consumption, the clocks to modules not being used can be halted by using differ ent sleep modes, as described in ?power management and sleep modes? on page 32. the clock systems are detailed below. figure 11. clock distribution cpu clock ? clk cpu the cpu clock is routed to parts of the system concerned with operation of the avr core. examples of such modules are the general purpose register file, the status reg- ister and the data memory holding the stack pointer. halting the cpu clock inhibits the core from performing general operations and calculations. i/o clock ? clk i/o the i/o clock is used by the majority of t he i/o modules, like timer/counters, spi, and usart. the i/o clock is also used by the external interrupt module, but note that some external interrupts are detected by asynchronous logic, allowing such interrupts to be detected even if the i/o clock is halted. also note that address recognition in the twi module is carried out asynchronously when clk i/o is halted, enabling twi address recep- tion in all sleep modes. flash clock ? clk flash the flash clock controls operation of the fl ash interface. the flash clock is usually active simultaneously with the cpu clock. general i/o modules asynchronous timer/counter adc cpu core ram clk i/o clk asy avr clock control unit clk cpu flash and eeprom clk flash clk adc source clock watchdog timer watchdog oscillator reset logic clock multiplexer watchdog clock calibrated rc oscillator timer/counter oscillator crystal oscillator low-frequency crystal oscillator external rc oscillator external clock
25 atmega8535(l) 2502k?avr?10/06 asynchronous timer clock ? clk asy the asynchronous timer clock allows the asynchronous timer/counter to be clocked directly from an external 32 khz clock cryst al. the dedicated clock domain allows using this timer/counter as a real-time counter even when the device is in sleep mode. adc clock ? clk adc the adc is provided with a dedicated clock domain. this allows halting the cpu and i/o clocks in order to reduce noise generated by digital circuitry. this gives more accu- rate adc conversion results. clock sources the device has the following clock source options, selectable by flash fuse bits as shown below. the clock from the selected source is input to the avr clock generator, and routed to the appropriate modules. note: 1. for all fuses ?1? means unprogrammed while ?0? means programmed. the various choices for each clocking option is given in the followi ng sections. when the cpu wakes up from power-down or power-save, the selected clock source is used to time the start-up, ensuring st able oscillator operation before instruction execution starts. when the cpu starts from reset, there is as an additional delay allowing the power to reach a stable level before commencing normal operation. the watchdog oscillator is used for timing this real-time part of the start-up time. the number of wdt oscillator cycles used for each time-out is shown in table 3. the frequency of the watchdog oscil- lator is voltage dependent as shown in ?atmega8535 typical characteristics? on page 266. default clock source the device is shipped with cksel = ?0001? and sut = ?10?. the default clock source setting is therefor e the internal rc oscillator with longe st startup time. this default set- ting ensures that all users can make their desired clock source setting using an in- system or parallel programmer. crystal oscillator xtal1 and xtal2 are input and output, respectively, of an inverting amplifier which can be configured for use as an on-chip oscillato r, as shown in figure 12. either a quartz crystal or a ceramic resonator may be used. the ckopt fuse selects between two dif- ferent oscillator am plifier modes. when ckopt is programmed, the oscillator output will oscillate will a full rail-to-rail swing on the output. this mode is suitable when operat- ing in a very noisy environment or when the output from xtal2 drives a second clock buffer. this mode has a wide frequency range. when ckopt is unprogrammed, the oscillator has a smaller output swing. this reduces power consumption considerably. table 2. device clocking options select (1) device clocking option cksel3..0 external crystal/ceramic resonator 1111 - 1010 external low-frequency crystal 1001 external rc oscillator 1000 - 0101 calibrated internal rc oscillator 0100 - 0001 external clock 0000 table 3. number of watchdog oscillator cycles typ time-out (v cc = 5.0v) typ time-out (v cc = 3.0v) number of cycles 4.1 ms 4.3 ms 4k (4,096) 65 ms 69 ms 64k (65,536)
26 atmega8535(l) 2502k?avr?10/06 this mode has a limited frequency range and it can not be used to drive other clock buffers. for resonators, the maximum frequency is 8 mhz with ckopt unprogrammed and 16 mhz with ckopt programmed. c1 and c2 sh ould always be equa l for both crystals and resonators. the optimal value of the capacitors depends on the crystal or resonator in use, the amount of stray capacitance, and the electromagnetic noise of the environ- ment. some initial guidelines for choosing capacitors for use with crystals are given in table 4. for ceramic resonators, the capacitor values given by the manufacturer should be used. figure 12. crystal oscillator connections the oscillator can operate in three different modes, each optimized for a specific fre- quency range. the operating mode is selected by the fuses cksel3..1 as shown in table 4. 2. this option should not be used with crystals, only with ceramic resonators. table 4. crystal oscillator operating modes ckopt cksel3..1 frequency range (mhz) recommended range for capacitors c1 and c2 for use with crystals (pf) 1 101 (2) 0.4 - 0.9 ? 1 110 0.9 - 3.0 12 - 22 1 111 3.0 - 8.0 12 - 22 0 101, 110, 111 1.0 - 16.0 12 - 22 xtal2 xtal1 gnd c2 c1
27 atmega8535(l) 2502k?avr?10/06 the cksel0 fuse together with the sut1..0 fuses select the start-up times as shown in table 5. notes: 1. these options should only be used wh en not operating close to the maximum fre- quency of the device, and only if frequency stabili ty at start-up is not important for the application. these options ar e not suitable for crystals. 2. these options are intended for use with ceramic resonators and will ensure fre- quency stability at start-up. they can also be used with crystals when not operating close to the maximum frequency of the device, and if frequency stability at start-up is not important for the application. table 5. start-up times for the crystal oscillator clock selection cksel0 sut1..0 start-up time from power-down and power-save additional delay from reset (v cc = 5.0v) recommended usage 000 258 ck (1) 4.1 ms ceramic resonator, fast rising power 001 258 ck (1) 65 ms ceramic resonator, slowly rising power 010 1k ck (2) ? ceramic resonator, bod enabled 011 1k ck (2) 4.1 ms ceramic resonator, fast rising power 100 1k ck (2) 65 ms ceramic resonator, slowly rising power 1 01 16k ck ? crystal oscillator, bod enabled 1 10 16k ck 4.1 ms crystal oscillator, fast rising power 1 11 16k ck 65 ms crystal oscillator, slowly rising power
28 atmega8535(l) 2502k?avr?10/06 low-frequency crystal oscillator to use a 32.768 khz watch crystal as the clock source for the device, the low-fre- quency crystal oscillator must be selected by setting the cksel fuses to ?1001?. the crystal should be connected as shown in figure 12. by programming the ckopt fuse, the user can enable internal capacitors on xtal1 and xtal2, thereby removing the need for external capacitors. the internal capacitors have a nominal value of 36 pf. when this oscillator is sele cted, start-up time s are determined by the sut fuses as shown in table 6. note: 1. these options should only be used if frequ ency stability at start-up is not important for the application. external rc oscillator for timing insensitive applications, the exte rnal rc configuration shown in figure 13 can be used. the frequency is roughly estima ted by the equation f = 1/(3rc). c should be at least 22 pf. by programming the ckopt fuse, the user can enable an internal 36 pf capacitor between xtal1 and gnd, thereby removing the need for an external capacitor. for more in formation on oscillato r operation and details on how to choose r and c, refer to the external rc oscillato r application note. figure 13. external rc configuration the oscillator can operate in four differ ent modes, each optimi zed for a specific fre- quency range. the operating mode is selected by the fuses cksel3..0 as shown in table 7. table 6. start-up times for the lo w-frequency crystal os cillator clock selection sut1..0 start-up time from power-down and power-save additional delay from reset (v cc = 5.0v) recommended usage 00 1k ck (1) 4.1 ms fast rising power or bod enabled 01 1k ck (1) 65 ms slowly rising power 10 32k ck 65 ms stable frequency at start-up 11 reserved xtal2 xtal1 gnd c r v cc nc
29 atmega8535(l) 2502k?avr?10/06 when this oscillator is sele cted, start-up time s are determined by the sut fuses as shown in table 8. note: 1. this option should not be used when operating close to the maximum frequency of the device. calibrated internal rc oscillator the calibrated internal rc oscillator provides a fixed 1.0, 2.0, 4.0, or 8.0 mhz clock. all frequencies are nominal values at 5v and 25 c. this clock may be selected as the sys- tem clock by programming the cksel fuses as shown in table 9. if selected, it will operate with no external components. the ckopt fuse should always be unpro- grammed when using this clock option. du ring reset, hardware loads the calibration byte into the osccal register and thereby automatically calibrates the rc oscillator. at 5v, 25 c and 1.0 mhz oscillator frequency sele cted, this calibration gives a fre- quency within 3% of the nominal frequency. using run-time calibration methods as described in application notes available at www.atmel.com/avr it is possible to achieve 1% accuracy at any given v cc and temperature. when this oscillator is used as the chip clock, the watchdog oscillator will still be used for the watchdog timer and for the reset time-out. for more information on the pre-programmed calibration value, see the section ?calibration byte? on page 239. note: 1. the device is shipped with this option selected. when this oscillator is selected, start-up times are determined by the sut fuses as shown in table 10. xtal1 and xtal2 should be left unconnected (nc). table 7. external rc oscilla tor operating modes cksel3..0 frequency range (mhz) 0101 0.1 - 0.9 0110 0.9 - 3.0 0111 3.0 - 8.0 1000 8.0 - 12.0 table 8. start-up times for the external rc oscillator clock selection sut1..0 start-up time from power-down and power-save additional delay from reset (v cc = 5.0v) recommended usage 00 18 ck ? bod enabled 01 18 ck 4.1 ms fast rising power 10 18 ck 65 ms slowly rising power 11 6 ck (1) 4.1 ms fast rising power or bod enabled table 9. internal calibrated rc o scillator operating modes cksel3..0 nominal frequency (mhz) 0001 (1) 1.0 0010 2.0 0011 4.0 0100 8.0
30 atmega8535(l) 2502k?avr?10/06 note: 1. the device is shipped with this option selected. oscillator calibration register ? osccal ? bits 7..0 ? cal7..0: oscillator calibration value writing the calibration byte to this address will trim the intern al oscillator to remove pro- cess variations from the osc illator frequency. duri ng reset, the 1 mhz calibration value which is located in the signature row high byte (address 0x00) is automatically loaded into the osccal register. if the internal rc is used at other frequencies, the calibration values must be loaded manually. this can be done by first reading the signature row by a programmer, and then store the calibrati on values in the flash or eeprom. then the value can be read by software and loaded into the osccal register. when osccal is zero, the lowe st available frequency is chosen. writing non-zero val- ues to this register will increa se the frequency of the intern al oscillator. writing 0xff to the register gives the highest available freq uency. the calibrated oscillator is used to time eeprom and flash access. if eeprom or flash is written, do not calibrate to more than 10% above the nominal frequency. otherwise, the eeprom or flash write may fail. note that the oscillator is intended for calibration to 1.0, 2.0, 4.0, or 8.0 mhz. tuning to other values is not guaranteed, as indicated in table 11. table 10. start-up times for the internal cali brated rc oscillator clock selection sut1..0 start-up time from power- down and power-save additional delay from reset (v cc = 5.0v) recommended usage 00 6 ck ? bod enabled 01 6 ck 4.1 ms fast rising power 10 (1) 6 ck 65 ms slowly rising power 11 reserved bit 76543210 cal7 cal6 cal5 cal4 cal3 cal2 cal1 cal0 osccal read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value device spec ific calibration value table 11. internal rc oscillator frequency range. osccal value min frequency in percentage of nominal frequency (%) max frequency in percentage of nominal frequency (%) 0x00 50 100 0x7f 75 150 0xff 100 200
31 atmega8535(l) 2502k?avr?10/06 external clock to drive the device from an external clock source, xtal1 should be driven as shown in figure 14. to run the device on an extern al clock, the cksel fuses must be pro- grammed to ?0000?. by programming the ckopt fuse, the user can enable an internal 36 pf capacitor between xtal1 and gnd. figure 14. external clock drive configuration when this clock source is selected, start- up times are determined by the sut fuses as shown in table 12. when applying an external clock, it is required to avoid sudden changes in the applied clock frequency to ensure stable operation of the mcu. a variation in frequency of more than 2% from one clock cycle to the next can lead to unpredictable behavior. it is required to ensure that the mcu is kept in reset during such changes in the clock frequency. timer/counter oscillator for avr microcontrollers with timer/counter oscillator pins (tosc1 and tosc2), the crystal is connected directly between the pi ns. no external capacitors are needed. the oscillator is optimized for use with a 32.768 khz watch crystal. applying an external clock source to tosc 1 is not recommended. table 12. start-up times for the external clock selection sut1..0 start-up time from power- down and power-save additional delay from reset (v cc = 5.0v) recommended usage 00 6 ck ? bod enabled 01 6 ck 4.1 ms fast rising power 10 6 ck 65 ms slowly rising power 11 reserved external clock signal
32 atmega8535(l) 2502k?avr?10/06 power management and sleep modes sleep modes enable the application to shut down unused modules in the mcu, thereby saving power. the avr provides various sleep modes allowing the user to tailor the power consumption to the application?s requirements. to enter any of the six sleep modes, the se bit in mcucr must be written to logic one and a sleep instruction must be executed. the sm2, sm1, and sm0 bits in the mcucr register select which sleep mode (idle, adc noise reduction, power-down, power-save, standb y, or extended st andby) will be ac tivated by the sleep instruction. see table 13 for a summary. if an enabled interrupt occurs while the mcu is in a sleep mode, the mcu wakes up. the mcu is then halted for four cycles in addition to the start-up time, it executes the interrupt routine, and resumes execution from the instruc- tion following sleep. the contents of the r egister file and sram are unaltered when the device wakes up from sleep. if a reset occurs during sleep mode, the mcu wakes up and executes from the reset vector. figure 11 on page 24 presents the different clock systems in the atmega8535, and their distribution. the figure is helpful in selecting an appropriate sleep mode. mcu control register ? mcucr the mcu control register contains control bits for power management. ? bits 7, 5, 4 ? sm2..0: sleep mode select bits 2, 1, and 0 these bits select between the six avail able sleep modes as shown in table 13. note: 1. standby mode and extended standby mode are only available with external crystals or resonators. ? bit 6 ? se: sleep enable the se bit must be written to logic one to make the mcu enter the sleep mode when the sleep instruction is executed. to avoid the mcu entering the sleep mode unless it is the programmers purpose, it is recommended to write the sleep enable (se) bit to one just before the execution of the sleep instruction and to cl ear it immediately after wak- ing up. bit 76543210 sm2 se sm1 sm0 isc11 isc10 isc01 isc00 mcucr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 table 13. sleep mode select sm2 sm1 sm0 sleep mode 000idle 0 0 1 adc noise reduction 010power-down 011power-save 100reserved 101reserved 110standby (1) 1 1 1 extended standby (1)
33 atmega8535(l) 2502k?avr?10/06 idle mode when the sm2..0 bits are written to 000, the sleep instruction makes the mcu enter idle mode, stopping the cpu but allowing spi, usart, analog comparator, adc, two- wire serial interface, timer/counters, wa tchdog, and the interrupt system to continue operating. this sleep mode basically halts clk cpu and clk flash , while allowing the other clocks to run. idle mode enables the mcu to wake up fr om external triggered interrupts as well as internal ones like the timer overflow and usart transmit complete interrupts. if wake-up from the analog comparator interrupt is not required, the analog comparator can be powered down by setting the adc bit in the analog comparator control and sta- tus register ? acsr. this will reduce power consumption in idle mode. if the adc is enabled, a conversion starts automatically when this mode is entered. adc noise reduction mode when the sm2..0 bits are written to 001, the sleep instruction makes the mcu enter adc noise reduction mode, stopping the cpu but allowing the adc, the external inter- rupts, the two-wire serial interface address watch, timer/counter2 and the watchdog to continue operating (if enabled). this sleep mode basically halts clk i/o , clk cpu , and clk- flash , while allowing the other clocks to run. this improves the noise environment for the adc, enabling higher resolution measure- ments. if the adc is enabled, a conversion starts automatically when this mode is entered. apart from the adc conversion complete interrupt, only an external reset, a watchdog reset, a brown-out reset, a two-wire serial interface address match inter- rupt, a timer/counter2 interrupt, an spm/eeprom ready interrupt, an external level interrupt on int0 or int1, or an external interrupt on int2 can wake up the mcu from adc noise reduction mode. power-down mode when the sm2..0 bits are written to 010, the sleep instruction makes the mcu enter power-down mode. in this mode, the external oscillator is stopped, while the external interrupts, the two-wire serial interface address watch, and the watchdog continue operating (if enabled). only an external reset, a watchdog reset, a brown-out reset, a two-wire serial interface address match interrupt, an external level interrupt on int0 or int1, or an external interrupt on int2 can wake up the mcu. this sleep mode basically halts all generated clocks, allowing operation of asynchronous modules only. note that if a level triggered interrupt is used for wake-up from power-down mode, the changed level must be held for some time to wake up the mcu. refer to ?external inter- rupts? on page 68 for details. when waking up from power-down mode, there is a delay from the wake-up condition occurs until the wake-up becomes effective. this allows the clock to restart and become stable after having been stopped. the wake-up period is defined by the same cksel fuses that define the reset time-out period, as described in ?clock sources? on page 25. power-save mode when the sm2..0 bits are written to 011, the sleep instruction makes the mcu enter power-save mode. this mode is identica l to power-down, with one exception: if timer/counter2 is clocked asynchronous ly, i.e., the as2 bit in assr is set, timer/counter2 will run during sleep. the device can wake up from either timer over- flow or output compare event from timer/counter2 if the corresponding timer/counter2 interrupt enable bits are set in timsk, and the global interrupt enable bit in sreg is set. if the asynchronous timer is not clocked asynchronously, power-down mode is recom- mended instead of power-save mode because the contents of the registers in the
34 atmega8535(l) 2502k?avr?10/06 asynchronous timer should be considered undefined after wake-up in power-save mode if as2 is 0. this sleep mode basically halts all clocks except clk asy , allowing operation only of asyn- chronous modules, including timer/counter2 if clocked asynchronously. standby mode when the sm2..0 bits are 110 and an external crystal/resonator clock option is selected, the sleep instruction makes the mcu enter standby mode. this mode is identical to power-down with the exception that the oscillator is kept running. from standby mode, the device wakes up in six clock cycles. extended standby mode when the sm2..0 bits are 111 and an external crystal/resonator clock option is selected, the sleep instruction makes the mcu enter extended standby mode. this mode is identical to power-save mode with the exception that the oscillator is kept running. from extended standby mode, the device wakes up in six clock cycles. notes: 1. external crystal or re sonator selected as clock source 2. if as 2 bit in assr is set 3. only int2 or level interrupt int1 and int0 table 14. active clock domains and wake-up sources in the different sleep modes. active clock domains oscillators wake up sources sleep mode clk cpu clk flash clk io clk adc clk asy main clock source enabled timer osc enabled int2 int1 int0 twi address match timer 2 spm/ eeprom ready a d c other i/o idle x x x x x (2) xx x xxx adc noise reduction xx x x (2) x (3) xx xx power- down x (3) x power- save x (2) x (2) x (3) xx (2) standby (1) xx (3) x extended standby (1) x (2) xx (2) x (3) xx (2)
35 atmega8535(l) 2502k?avr?10/06 minimizing power consumption there are several issues to consider when trying to minimize the power consumption in an avr controlled system. in general, sleep modes should be used as much as possi- ble, and the sleep mode should be selected so that as few as pos sible of the device?s functions are operating. all functions not needed should be disabled. in particular, the following modules may need special consider ation when trying to achieve the lowest possible power consumption. analog-to-digital converter if enabled, the adc will be enabled in all sleep modes. to save power, the adc should be disabled before entering any sleep mode. when the adc is turned off and on again, the next conversion will be an extended conversion. refer to ?analog-to-digital con- verter? on page 206 for details on adc operation. analog comparator when entering idle mode, the analog comparator should be disabled if not used. when entering adc noise reduction mode, the analog comparator should be disabled. in the other sleep modes, the analog comparator is automatically disabled. however, if the analog comparator is set up to use the internal voltage reference as input, the analog comparator should be disabled in all sleep modes. otherwise, the internal voltage ref- erence will be enabled, independent of sleep mode. refer to ?analog comparator? on page 203 for details on how to configure the analog comparator. brown-out detector if the brown-out detector is not needed in the application, this module should be turned off. if the brown-out detector is enabled by the boden fuse, it will be enabled in all sleep modes, and hence, always consume power. in the deeper sleep modes, this will contribute significantly to the total current consumption. refer to ?brown-out detection? on page 39 for details on how to configure the brown-out detector. internal voltage reference the internal voltage reference will be enabled when needed by the brown-out detec- tor, the analog comparator or the adc. if these modules are disabled as described in the sections above, the internal voltage reference will be disabled and it will not be con- suming power. when turned on again, the user must allow the reference to start up before the output is used. if the reference is kept on in sleep mode, the output can be used immediately. refer to ?internal voltage reference? on page 41 for details on the start-up time. watchdog timer if the watchdog timer is not needed in the application, this module should be turned off. if the watchdog timer is enabled, it will be enabled in all sleep modes, and hence, always consume power. in the deeper sleep modes, this will contribute significantly to the total current consumption. refer to ?watchdog timer? on page 41 for details on how to configure the watchdog timer. port pins when entering a sleep mode, all port pins should be configured to use minimum power. the most important thing is then to ensure that no pins drive resistive loads. in sleep modes where both the i/o clock (clk i/o ) and the adc clock (clk adc ) are stopped, the input buffers of the de vice will be disabled. this ensure s that no power is consumed by the input logic when not needed. in some cases, the input logic is needed for detecting wake-up conditions, and it will then be enabled. refer to the section ?digital input enable and sleep modes? on page 55 for details on which pins are enabled. if the input buffer is enabled and the input signal is le ft floating or have an analog signal level close to v cc /2, the input buffer will use excessive power.
36 atmega8535(l) 2502k?avr?10/06 system control and reset resetting the avr during reset, all i/o registers are set to their initial values, and the program starts exe- cution from the reset vector. the instruction placed at the reset vector must be an rjmp instruction to the reset handling routine. if the program never enables an interrupt source, the interrupt vectors are not used, and regular program code can be placed at these locations. this is also the case if the reset vector is in the application section while the interrupt vectors are in the boot section or vice versa. the circuit diagram in figure 15 shows the reset logic. table 15 def ines the electrical parameters of the reset circuitry. the i/o ports of the avr are immediately reset to their initial state when a reset source goes active. this does not require any clock source to be running. after all reset sources have gone inactive, a delay counter is invoked, stretching the internal reset. this allows the power to reach a stable level before normal operation starts. the time-out period of the delay counter is defined by the user through the cksel fuses. the different selections for the delay period are presented in ?clock sources? on page 25. reset sources the atmega8535 has four sources of reset: ? power-on reset. the mcu is reset when the supply voltage is below the power-on reset threshold (v pot ). ? external reset. the mcu is reset when a low level is present on the reset pin for longer than the minimum pulse length. ? watchdog reset. the mcu is reset when the watchdog timer period expires and the watchdog is enabled. ? brown-out reset. the mcu is reset when the supply voltage v cc is below the brown-out reset threshold (v bot ) and the brown-out detector is enabled.
37 atmega8535(l) 2502k?avr?10/06 figure 15. reset logic notes: 1. values are guidelines only. 2. the power-on reset will not work unless the supply voltage has been below v pot (falling). table 15. reset characteristics symbol parameter condition min (1) typ (1) max (1) units v pot power-on reset threshold voltage (rising) 1.4 2.3 v power-on reset threshold voltage (falling) (2) 1.3 2.3 v v rst reset pin threshold voltage 0.2 0.9 v t rst minimum pulse width on reset pin 1.5 s v bot brown-out reset threshold voltage (3) bodlevel = 1 2.5 2.7 2.9 v bodlevel = 0 3.6 4.0 4.2 t bod minimum low voltage period for brown-out detection bodlevel = 1 2 s bodlevel = 0 2 s v hyst brown-out detector hysteresis 130 mv mcu control and status register (mcucsr) brown-out reset circuit boden bodlevel delay counters cksel[3:0] ck timeout wdrf borf extrf porf data b u s clock generator spike filter pull-up resistor watchdog oscillator sut[1:0] power-on reset circuit reset circuit watchdog timer
38 atmega8535(l) 2502k?avr?10/06 3. v bot may be below nominal minimum operating voltage for some devices. for devices where this is the case, t he device is tested down to v cc = v bot during the production test. this guarantees that a brown-out reset will occur before v cc drops to a voltage where correct operation of the microcontroller is no longer guaranteed. the test is performed using bodlevel = 1 for atmega8535l and bodlevel = 0 for atmega8535. bodlevel = 1 is not applicable for atmega8535. power-on reset a power-on reset (por) pulse is generated by an on-chip detection circuit. the detec- tion level is defined in table 15. the por is activated whenever v cc is below the detection level. the por circuit can be used to trigger the start-up reset, as well as to detect a failure in supply voltage. a power-on reset (por) circuit ensures that the device is reset from power-on. reach- ing the power-on reset threshold voltage invokes the delay counter, which determines how long the device is kept in reset after v cc rise. the reset signal is activated again, without any delay, when v cc decreases below t he detection level. figure 16. mcu start-up, reset tied to v cc figure 17. mcu start-up, reset extended externally v reset time-out internal reset t tout v pot v rst cc reset time-out internal reset t tout v pot v rst v cc
39 atmega8535(l) 2502k?avr?10/06 external reset an external reset is generated by a low level on the reset pin. reset pulses longer than the minimum pulse width (see table 15) will generate a reset, even if the clock is not running. shorter pulses are not guaranteed to generate a reset. when the applied signal reaches the reset threshold voltage ? v rst on its positive edge, the delay counter starts the mcu after the time-out period t tout has expired. figure 18. external reset during operation brown-out detection atmega8535 has an on-chip brown-out detection (bod) circuit for monitoring the v cc level during operation by comparing it to a fi xed trigger level. the trigger level for the bod can be selected by the fuse bodle vel to be 2.7v (bod level unprogrammed), or 4.0v (bodlevel programmed). the trigger level has a hysteresis to ensure spike free brown-out detection. the hysteresis on the detection level should be interpreted as v bot+ = v bot + v hyst /2 and v bot- = v bot - v hyst /2. the bod circuit can be enabled/disabled by the fuse boden. when the bod is enabled (boden programmed), and v cc decreases to a value below the trigger level (v bot- in figure 19), the brown-out reset is immediately activated. when v cc increases above the trigger level (v bot+ in figure 19), the delay counter starts the mcu after the time-out period t tout has expired. the bod circuit will only detect a drop in v cc if the voltage stays below the trigger level for longer than t bod given in table 15. figure 19. brown-out reset during operation cc v cc reset time-out internal reset v bot- v bot+ t tout
40 atmega8535(l) 2502k?avr?10/06 watchdog reset when the watchdog times out, it will generate a short rese t pulse of one ck cycle dura- tion. on the falling edge of this pulse, the delay timer starts counting the time-out period t tout . refer to page 41 for details on operation of the watchdog timer. figure 20. watchdog reset during operation mcu control and status register ? mcucsr the mcu control and status register provides information on which reset source caused an mcu reset. ? bit 3 ? wdrf: watchdog reset flag this bit is set if a watchdog reset occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 2 ? borf: brown-out reset flag this bit is set if a brown-out reset occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 1 ? extrf: external reset flag this bit is set if an external reset occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 0 ? porf: power-on reset flag this bit is set if a power-on reset occurs. th e bit is reset only by writing a logic zero to the flag. to make use of the reset flags to identify a reset condition, the user should read and then reset the mcucsr as early as possible in the program. if the register is cleared before another reset occurs, the source of the reset can be found by examining the reset flags. ck cc bit 76543210 ? isc2 ? ? wdrf borf extrf porf mcucsr read/write r/w r/w r r/w r/w r/w r/w r/w initial value 0 0 0 see bit description
41 atmega8535(l) 2502k?avr?10/06 internal voltage reference atmega8535 features an internal bandgap reference. this reference is used for brown- out detection, and it can be used as an input to the analog comparator or the adc. the 2.56v reference to the adc is generated from the internal bandgap reference. voltage reference enable signals and start-up time the voltage reference has a start-up time that may influence the way it should be used. the start-up time is given in table 16. to save power, the reference is not always turned on. the reference is on during the following situations: 1. when the bod is enabled (by programming the boden fuse). 2. when the bandgap reference is connected to the analog comparator (by setting the acbg bit in acsr). 3. when the adc is enabled. thus, when the bod is not enabled, after setting the acbg bit or enabling the adc, the user must always allow the reference to start up before the output from the analog com- parator or adc is used. to reduce power consumption in power-down mode, the user can avoid the three conditions above to ensure that the reference is turned off before entering power-down mode. note: 1. values are guidelines only. watchdog timer the watchdog timer is clocked from a separate on-chip oscillator which runs at 1 mhz. this is the typical value at v cc = 5v. see characterization data for typical values at other v cc levels. by controlling the watchdog timer prescaler, the watchdog reset interval can be adjusted as shown in table 18 on page 43. the wdr ? watchdog reset ? instruction resets the watchdog timer. the watchdog timer is also reset when it is disabled and when a chip reset occurs. ei ght different clock cycle periods can be selected to determine the reset period. if the reset period expires without another watchdog reset, the atmega8535 resets and executes from the reset vector. for tim- ing details on the watchdog reset, refer to page 40. to prevent unintentional disabling of the watchdog or unintentional change of time-out period, three different safety levels are selected by the fuses s8535c and wdton as shown in table 17. safety level 0 corresponds to the setting in at90s8535. there is no restriction on enabling the wdt in any of the safety levels. table 16. internal voltage reference characteristics (1) symbol parameter min typ max units v bg bandgap reference voltage 1.15 1.23 1.35 v t bg bandgap reference start-up time 40 70 s i bg bandgap reference current consumption 10 a
42 atmega8535(l) 2502k?avr?10/06 figure 21. watchdog timer watchdog timer control register ? wdtcr ? bits 7..5 ? res: reserved bits these bits are reserved bits in the atmega8535 and will always read as zero. ? bit 4 ? wdce: watchdog change enable this bit must be set when the wde bit is written to logic zero. otherwise, the watchdog will not be disabled. once written to one, har dware will clear this bit after four clock cycles. refer to the description of the wde bit for a watchdog disable procedure. in safety level 1 and 2, this bit must also be set when changing the prescaler bits. see ?timed sequences for changing the configuration of the watchdog timer? on page 45. ? bit 3 ? wde: watchdog enable when the wde is written to logic one, the watchdog timer is enabled, and if the wde is written to logic zero, the watchdog timer function is disabled. wde can only be cleared table 17. wdt configuration as a function of the fuse settings of s8538c and wdton s8535c wdton safety level wdt initial state how to disable the wdt how to change time-out unprogrammed unprogrammed 1 disabled timed sequence timed sequence unprogrammed programmed 2 enabled always enabled timed sequence programmed unprogrammed 0 disabled timed sequence no restriction programmed programmed 2 enabled always enabled timed sequence watchdog oscillator bit 76543210 ? ? ? wdce wde wdp2 wdp1 wdp0 wdtcr read/write r r r r/w r/w r/w r/w r/w initial value00000000
43 atmega8535(l) 2502k?avr?10/06 if the wdce bit has logic level one. to disable an enabled watchdog timer, the follow- ing procedure must be followed: 1. in the same operation, write a logic one to wdce and wde. a logic one must be written to wde even though it is set to one before the disable operation starts. 2. within the next four clock cycles, write a logic 0 to wde. this disables the watchdog. in safety level 2, it is not possible to disable the watchdog timer, even with the algo- rithm described above. see ?timed sequences for changing the configuration of the watchdog timer? on page 45. ? bits 2..0 ? wdp2, wdp1, wdp0: watchdog timer prescaler 2, 1, and 0 the wdp2, wdp1, and wdp0 bits determine the watchdog timer prescaling when the watchdog timer is enabled. the different prescaling values and their corresponding timeout periods are shown in table 18. note: 1. values are guidelines only. table 18. watchdog timer prescale select (1) wdp2 wdp1 wdp0 number of wdt oscillator cycles typical time-out at v cc = 3.0v typical time-out at v cc = 5.0v 0 0 0 16k (16,384) 17.1 ms 16.3 ms 0 0 1 32k (32,768) 34.3 ms 32.5 ms 0 1 0 64k (65,536) 68.5 ms 65 ms 0 1 1 128k (131,072) 0.14 s 0.13 s 1 0 0 256k (262,144) 0.27 s 0.26 s 1 0 1 512k (524,288) 0.55 s 0.52 s 1 1 0 1,024k (1,048,576) 1.1 s 1.0 s 1 1 1 2,048k (2,097,152) 2.2 s 2.1 s
44 atmega8535(l) 2502k?avr?10/06 the following code example shows one assembly and one c function for turning off the wdt. the example assumes that interrupts are controlled (e.g., by disabling interrupts globally) so that no inte rrupts will occur during execution of these functions. assembly code example wdt_off: ; reset wdt wdr ; write logical one to wdce and wde in r16, wdtcr ori r16, (1< 45 atmega8535(l) 2502k?avr?10/06 timed sequences for changing the configuration of the watchdog timer the sequence for changing the watchdog timer configuration differs slightly between the three safety levels. separate procedures are described for each level. safety level 0 this mode is compatible with the watchdog operation found in at90s8535. the watch- dog timer is initially disabled, but can be enabled by writing the wde bit to 1 without any restriction. the time-out period can be changed at any time without restriction. to disable an enabled watchdog timer and/or changing the watchdog time-out, the fol- lowing procedure must be followed: 1. in the same operation, write a logic one to wdce and wde. a logic one must be written to wde regardless of the previous value of the wde bit. 2. within the next four clock cycles, in the same operation, write the wde and wdp bits as desired, but with the wdce bit cleared. safety level 1 in this mode, the watchdog timer is initially disabled, but can be enabled by writing the wde bit to 1 without any restriction. a timed sequence is needed when changing the watchdog time-out period or disabling an enabled watchdog timer. to disable an enabled watchdog timer and/or changing t he watchdog time-out, the following proce- dure must be followed: 1. in the same operation, write a logic one to wdce and wde. a logic one must be written to wde regardless of the previous value of the wde bit. 2. within the next four clock cycles, in the same operation, write the wde and wdp bits as desired, but with the wdce bit cleared. safety level 2 in this mode, the watchdog timer is alwa ys enabled, and the wde bit will always read as one. a timed sequence is needed when changing the watchdog time-out period. to change the watchdog time-out, the following procedure must be followed: 1. in the same operation, write a logical one to wdce and wde. even though the wde always is set, the wde must be writ ten to one to start the timed sequence. 2. within the next four clock cycles, in the same operation, write the wdp bits as desired, but with the wdce bit cleared. the value written to the wde bit is irrelevant.
46 atmega8535(l) 2502k?avr?10/06 interrupts this section describes the specifics of the interrupt handling as performed in atmega8535. for a general explanation of the avr interrupt handling, refer to ?reset and interrupt handling? on page 13. interrupt vectors in atmega8535 notes: 1. when the bootrst fuse is programmed, the device will jump to the boot loader address at reset, see ?boot loader support ? read-while-write self-programming? on page 224. 2. when the ivsel bi t in gicr is set, interrupt vectors will be moved to the start of the boot flash section. the addr ess of each interrupt vector will then be the address in this table added to the start address of the boot flash section. table 20 shows reset and interrupt vectors placement for the various combinations of bootrst and ivsel settings. if the program never enables an inte rrupt source, the interrupt vectors are not used, and regular program code can be placed at these loca- tions. this is also the case if the reset ve ctor is in the applic ation section while the interrupt vectors are in the boot section or vice versa. table 19. reset and interrupt vectors vector no. program address (2) source interrupt definition 1 0x000 (1) reset external pin, power-on reset, brown-out reset and watchdog reset 2 0x001 int0 external interrupt request 0 3 0x002 int1 external interrupt request 1 4 0x003 timer2 comp timer/ counter2 compare match 5 0x004 timer2 ovf timer/counter2 overflow 6 0x005 timer1 capt timer/counter1 capture event 7 0x006 timer1 compa timer/counter1 compare match a 8 0x007 timer1 compb timer/counter1 compare match b 9 0x008 timer1 ovf timer/counter1 overflow 10 0x009 timer0 ovf timer/counter0 overflow 11 0x00a spi, stc serial transfer complete 12 0x00b usart, rxc usart, rx complete 13 0x00c usart, udre usart data register empty 14 0x00d usart, txc usart, tx complete 15 0x00e adc adc conversion complete 16 0x00f ee_rdy eeprom ready 17 0x010 ana_comp analog comparator 18 0x011 twi two-wire serial interface 19 0x012 int2 external interrupt request 2 20 0x013 timer0 comp timer/counter0 compare match 21 0x014 spm_rdy store program memory ready
47 atmega8535(l) 2502k?avr?10/06 note: 1. the boot reset address is shown in table 93 on page 235. for the bootrst fuse ?1? means unprogrammed while ?0? means programmed. the most typical and general program setup for the reset and interrupt vector addresses in atmega8535 is: addresslabels code comments 0x000 rjmp reset ; reset handler 0x001 rjmp ext_int0 ; irq0 handler 0x002 rjmp ext_int1 ; irq1 handler 0x003 rjmp tim2_comp ; timer2 compare handler 0x004 rjmp tim2_ovf ; timer2 overflow handler 0x005 rjmp tim1_capt ; timer1 capture handler 0x006 rjmp tim1_compa ; timer1 compare a handler 0x007 rjmp tim1_compb ; timer1 compare b handler 0x008 rjmp tim1_ovf ; timer1 overflow handler 0x009 rjmp tim0_ovf ; timer0 overflow handler 0x00a rjmp spi_stc ; spi transfer complete handler 0x00b rjmp usart_rxc ; usart rx complete handler 0x00c rjmp usart_udre ; udr empty handler 0x00d rjmp usart_txc ; usart tx complete handler 0x00e rjmp adc ; adc conversion complete handler 0x00f rjmp ee_rdy ; eeprom ready handler 0x010 rjmp ana_comp ; analog comparator handler 0x011 rjmp twsi ; two-wire serial interface handler 0x012 rjmp ext_int2 ; irq2 handler 0x013 rjmp tim0_comp ; timer0 compare handler 0x014 rjmp spm_rdy ; store program memory ready handler ; 0x015 reset: ldi r16,high(ramend) ; main program start 0x016 out sph,r16 ; set stack pointer to top of ram 0x017 ldi r16,low(ramend) 0x018 out spl,r16 0x019 sei ; enable interrupts 0x020 xxx ... ... ... when the bootrst fuse is unprogrammed, the boot section size set to 2k bytes and the ivsel bit in the gicr regi ster is set before any inte rrupts are enabled, the most typical and general program setup for the reset and interrupt vector addresses is: table 20. reset and interrupt vectors placement bootrst (1) ivsel reset address interrupt vectors start address 1 0 0x0000 0x0001 1 1 0x0000 boot reset address + 0x0001 0 0 boot reset address 0x0001 0 1 boot reset address boot reset address + 0x0001
48 atmega8535(l) 2502k?avr?10/06 addresslabels code comments 0x000 reset: ldi r16,high(ramend) ; main program start 0x001 out sph,r16 ; set stack pointer to top of ram 0x002 ldi r16,low(ramend) 0x003 out spl,r16 0x004 sei ; enable interrupts 0x005 xxx ; .org 0xc01 0xc01 rjmp ext_int0 ; irq0 handler 0xc02 rjmp ext_int1 ; irq1 handler ... .... .. ; 0xc14 rjmp spm_rdy ; store program memory ready handler when the bootrst fuse is programmed and the boot section size set to 2k bytes, the most typical and general program setup for the reset and interrupt vector addresses is: addresslabels code comments .org 0x001 0x001 rjmp ext_int0 ; irq0 handler 0x002 rjmp ext_int1 ; irq1 handler ... ... . .. ; 0x014 rjmp spm_rdy ; store program memory ready handler ; .org 0xc00 0xc00 reset: ldi r16,high(ramend) ; main program start 0xc01 out sph,r16 ; set stack pointer to top of ram 0xc02 ldi r16,low(ramend) 0xc03 out spl,r16 0xc04 sei ; enable interrupts 0xc05 xxx when the bootrst fuse is programmed, the boot section size set to 2k bytes and the ivsel bit in the gicr register is set before any interrupts are enabled, the most typical and general program setup for the reset and interrupt vector addresses is: addresslabels code comments .org 0xc00 0xc00 rjmp reset ; reset handler 0xc01 rjmp ext_int0 ; irq0 handler 0xc02 rjmp ext_int1 ; irq1 handler ... ... . .. ; 0xc14 rjmp spm_rdy ; store program memory ready handler ; 0xc15 reset: ldi r16,high(ramend) ;main program start 0xc16 out sph,r16 ; set stack pointer to top of ram 0xc17 ldi r16,low(ramend) 0xc18 out spl,r16 0xc19 sei ; enable interrupts 0xc20 xxx
49 atmega8535(l) 2502k?avr?10/06 moving interrupts between application and boot space the general interrupt control register controls the placement of the interrupt vector table. general interrupt control register ? gicr ? bit 1 ? ivsel: interrupt vector select when the ivsel bit is cleared (zero), the interrupt vectors ar e placed at the start of the flash memory. when this bit is set (one), the interrupt vectors are moved to the begin- ning of the boot loader section of the flash. the actual address of the start of the boot flash section is determined by the bootsz fuses. refer to the section ?boot loader support ? read-while-write self-programming? on page 224 for details. to avoid unin- tentional changes of interrupt vector tables, a special write procedure must be followed to change the ivsel bit: 1. write the interrupt vector change enable (ivce) bit to one. 2. within four cycles, write the desired valu e to ivsel while writing a zero to ivce. interrupts will automatically be disabled while this sequence is executed. interrupts are disabled in the cycle ivce is set, and they remain disabled until after the instruction fol- lowing the write to ivsel. if ivsel is not written, interrupts remain disabled for four cycles. the i-bit in the status register is unaffected by the automatic disabling. note: if interrupt vectors are placed in the boot loader section and boot lock bit blb02 is pro- grammed, interrupts are disabled while executing from the application section. if interrupt vectors are placed in the applicat ion section and boot lock bit blb12 is pro- gramed, interrupts are disabled while executin g from the boot loader section. refer to the section ?boot loader support ? read-wh ile-write self-programming? on page 224 for details on boot lock bits. ? bit 0 ? ivce: interrupt vector change enable the ivce bit must be written to logic one to enable change of the ivsel bit. ivce is cleared by hardware four cycles after it is written or when ivsel is written. setting the ivce bit will disable interrupts, as explain ed in the ivsel descri ption above. see code example below. bit 76543210 int1 int0 int2 ? ? ? ivsel ivce gicr read/write r/w r/w r/w r r r r/w r/w initial value 0 0 0 0 0 0 0 0
50 atmega8535(l) 2502k?avr?10/06 assembly code example move_interrupts: ; enable change of interrupt vectors ldi r16, (1< 51 atmega8535(l) 2502k?avr?10/06 i/o-ports introduction all avr ports have true read-modify-write functionality when used as general digital i/o ports. this means that the direction of one port pin can be changed without uninten- tionally changing the direction of any other pin with the sbi and cbi instructions. the same applies when changing drive value (if c onfigured as output) or enabling/disabling of pull-up resistors (if configured as input). each output buffer has symmetrical drive characteristics with both high sink and source capability. the pin dr iver is strong enough to drive led displays directly. all port pins have individually selectable pull-up resistors with a supply-voltage invariant resistance. all i/o pins have protection diodes to both v cc and ground as indicated in figure 22. refer to ?electrical characteristics? on page 255 for a complete list of parameters. figure 22. i/o pin equivalent schematic all registers and bit references in this section are written in general form. a lower case ?x? represents the numbering letter for the port, and a lower case ?n? represents the bit number. however, when using the register or bit defines in a program, the precise form must be used. for example, portb3 for bit no. 3 in port b, here documented generally as portxn. the physical i/o registers and bit locations are listed in ?register descrip- tion for i/o-ports? on page 66. three i/o memory address locations are allocated for each port, one each for the data register ? portx, data direction register ? ddrx, and the port input pins ? pinx. the port input pins i/o location is read only, while the data register and the data direction register are read/write. in addition, the pull-up disable ? pud bit in sfior disables the pull-up function for all pins in all ports when set. using the i/o port as general dig ital i/o is described in ?ports as general digital i/o? on page 52. most port pins are multiplexed with alternate functions for the peripheral fea- tures on the device. how each alternate function interferes with the port pin is described in ?alternate port functions? on page 57. refer to the individual module sections for a full description of the alternate functions. note that enabling the alternate function of some of the port pins does not affect the use of the other pins in the port as general digital i/o. c pin logic r pu see figure "general digital i/o" fo r details pxn
52 atmega8535(l) 2502k?avr?10/06 ports as general digital i/o the ports are bi-directional i/o ports with optional internal pull-ups. figure 23 shows a functional description of one i/o-port pin, here generically called pxn. figure 23. general digital i/o (1) note: 1. wpx, wdx, rrx, rpx, and rdx are common to all pins within the same port. clk i/o , sleep, and pud are common to all ports. configuring the pin each port pin consists of three register bits: ddxn, portxn, and pinxn. as shown in ?register description for i/o-ports? on page 66, the ddxn bits are accessed at the ddrx i/o address, the portxn bits at t he portx i/o address, and the pinxn bits at the pinx i/o address. the ddxn bit in the ddrx register selects the direction of this pin. if ddxn is written logic one, pxn is configured as an output pin. if ddxn is written logic zero, pxn is config- ured as an input pin. if portxn is written a logic one when the pin is configured as an input pin, the pull-up resistor is activated. to switch the pull-up resistor off, portxn has to be written logic zero or the pin has to be configured as an output pin. the port pins are tri-stated when a reset condition becomes active, even if no clocks are running. if portxn is written a logic one when the pin is configured as an output pin, the port pin is driven high (one). if portxn is written a logic zero when the pin is configured as an output pin, the port pin is driven low (zero). when switching between tri-state ({ddxn, portxn} = 0b00) and output high ({ddxn, portxn} = 0b11), an intermediate state with either pull-up enabled ({ddxn, portxn} = clk rpx rrx wpx rdx wdx pud synchronizer wdx: write ddrx wpx: write portx rrx: read portx register rpx: read portx pin pud: pullup disable clk i/o : i/o clock rdx: read ddrx d l q q reset reset q q d q q d clr portxn q q d clr ddxn pinxn data b u s sleep sleep: sleep control pxn i/o
53 atmega8535(l) 2502k?avr?10/06 0b01) or output low ({ddxn, portxn} = 0b10) must occur. normally, the pull-up enabled state is fully acceptable, as a high -impedant environment will not notice the dif- ference between a strong high driver and a pull-up. if this is not the case, the pud bit in the sfior register can be set to disable all pull-ups in all ports. switching between input with pull-up and output low generates the same problem. the user must use either the tri-state ({ddxn, portxn} = 0b00) or the output high state ({ddxn, portxn} = 0b10) as an intermediate step. table 21 summarizes the control signals for the pin value. reading the pin value independent of the setting of data direction bit ddxn, the port pin can be read through the pinxn register bit. as shown in figure 23, the pinxn register bit and the preceding latch constitute a synchronizer. this is needed to avoid metastability if the physical pin changes value near the edge of the internal cl ock, but it also introduces a delay. figure 24 shows a timing diagram of the synchroni zation when reading an externally applied pin value. the maximum and minimum propagation delays are denoted t pd,max and t pd,min respectively. figure 24. synchronization when reading an externally applied pin value consider the clock period starting shortly after the first falling edge of the system clock. the latch is closed when the clock is low, and goes transparent when the clock is high, as indicated by the shaded region of t he ?sync latch? signal. the signal value is latched when the system clock goes low. it is clocked into the pinxn register at the suc- table 21. port pin configurations ddxn portxn pud (in sfior) i/o pull-up comment 0 0 x input no tri-state (hi-z) 0 1 0 input yes pxn will source current if ext. pulled low. 0 1 1 input no tri-state (hi-z) 1 0 x output no output low (sink) 1 1 x output no output high (source) xxx in r17, pinx 0x00 0xff instructions sync latch pinxn r17 xxx system clk t pd, max t pd, min
54 atmega8535(l) 2502k?avr?10/06 ceeding positive clock edge. as indicated by the two arrows t pd,max and t pd,min , a single signal transition on the pin will be delay ed between ? and 1? system clock period depending upon the time of assertion. when reading back a software assigned pin value, a nop instruction must be inserted as indicated in figure 25. the out instruction sets the ?sync latch? signal at the positive edge of the clock. in this case, the delay t pd through the synchronizer is one system clock period. figure 25. synchronization when reading a software assigned pin value out portx, r16 nop in r17, pinx 0xff 0x00 0xff system clk r16 instructions sync latch pinxn r17 t pd
55 atmega8535(l) 2502k?avr?10/06 the following code example shows how to set port b pins 0 and 1 high, 2 and 3 low, and define the port pins from 4 to 7 as input with pull-ups assigned to port pins 6 and 7. the resulting pin values are read back again, but as previously discussed, a nop instruction is included to be able to read back the value recently assigned to some of the pins. note: 1. for the assembly program, two temporary registers are used to minimize the time from pull-ups are set on pins 0, 1, 6, and 7, until the direction bits are correctly set, defining bits 2 and 3 as low and redefining bits 0 and 1 as strong high drivers. digital input enable and sleep modes as shown in figure 23, the digital input si gnal can be clamped to ground at the input of the schmitt trigger. the signal denoted sleep in the figure, is set by the mcu sleep controller in power-down mode, power-save mode, standby mode, and extended standby mode to avoid high power consumption if some input signals are left floating, or have an analog signal level close to v cc /2. sleep is overridden for port pins enabled as external interrupt pins. if the external interrupt request is not enabled, sleep is ac tive also for these pins. sleep is also overridden by various other alternate functions as described in ?alternate port func- tions? on page 57. if a logic high level (?one?) is present on an asynchronous external interrupt pin config- ured as ?interrupt on rising edge, falling edge, or any logic change on pin? while the external interrupt is not enabled, the corresponding exte rnal interrupt flag will be set assembly code example (1) ... ; define pull-ups and set outputs high ; define directions for port pins ldi r16,(1< 56 atmega8535(l) 2502k?avr?10/06 when resuming from the above mentioned sl eep modes, as the clamping in these sleep modes produces the requested logic change. unconnected pins if some pins are unused, it is recommended to ensure that these pins have a defined level. even though most of the digital inputs are disabled in the deep sleep modes as described above, floating inputs should be av oided to reduce current consumption in all other modes where the digital inputs are en abled (reset, active mode and idle mode). the simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up. in this case, the pull-up will be disabled during reset. if low power consumption during reset is important, it is recommended to use an external pull-up or pull-down. connecting unused pins directly to v cc or gnd is not recommended, since this may cause excessive currents if the pin is accidentally configured as an output.
57 atmega8535(l) 2502k?avr?10/06 alternate port functions most port pins have alternate functions in addition to being general digital i/os. figure 26 shows how the port pin control signals fr om the simplified figure 23 can be overrid- den by alternate functions. the overriding signals may not be present in all port pins, but the figure serves as a generic description app licable to all port pins in the avr micro- controller family. figure 26. alternate port functions (1) note: 1. wpx, wdx, rrx, rpx, and rdx are common to all pins within the same port. clk i/o , sleep, and pud are common to all ports. all other signals are unique for each pin. clk rpx rrx wpx rdx wdx pud synchronizer wdx: write ddrx wpx: write portx rrx: read portx register rpx: read portx pin pud: pullup disable clk i/o : i/o clock rdx: read ddrx d l q q set clr 0 1 0 1 0 1 dixn aioxn dieoexn pvovxn pvoexn ddovxn ddoexn puoexn puovxn puoexn: pxn pull-up override enable puovxn: pxn pull-up override value ddoexn: pxn data direction override enable ddovxn: pxn data direction override value pvoexn: pxn port value override enable pvovxn: pxn port value override value dixn: digital input pin n on portx aioxn: analog input/output pin n on portx reset reset q q d clr q q d clr q q d clr pinxn portxn ddxn data b u s 0 1 dieovxn sleep dieoexn: pxn digital input-enable override enable dieovxn: pxn digital input-enable override value sleep: sleep control pxn i/o
58 atmega8535(l) 2502k?avr?10/06 table 22 summarizes the function of the overriding signals. the pin and port indexes from figure 26 are not shown in the succeed ing tables. the overriding signals are gen- erated internally in the modules having the alternate function. the following subsections shortly describe the alternate functions for each port, and relate the overriding signals to the alternat e function. refer to the alternate function description for further details. table 22. generic description of overriding signals for alternate functions signal name full name description puoe pull-up override enable if this signal is set, the pull-up enable is controlled by the puov signal. if this signal is cleared, the pull-up is enabled when {ddxn, portxn, pud} = 0b010. puov pull-up override value if puoe is set, the pull-up is enabled/disabled when puov is set/cleared, regardless of the setting of the ddxn, portxn, and pud register bits. ddoe data direction override enable if this signal is set, the output driver enable is controlled by the ddov signal. if this signal is cleared, the output driver is enabled by the ddxn register bit. ddov data direction override value if ddoe is set, the output driver is enabled/disabled when ddov is set/cleared, regardless of the setting of the ddxn register bit. pvoe port value override enable if this signal is set and the output driver is enabled, the port value is controlled by the pvov signal. if pvoe is cleared, and the output driver is enabled, the port value is controlled by the portxn register bit. pvov port value override value if pvoe is set, the port value is set to pvov, regardless of the setting of the portxn register bit. dieoe digital input enable override enable if this bit is set, the digital i nput enable is controlled by the dieov signal. if this signal is cl eared, the digital input enable is determined by mcu-state (normal mode, sleep modes). dieov digital input enable override value if dieoe is set, the digital input is enabled/disabled when dieov is set/cleared, regardless of the mcu state (normal mode, sleep modes). di digital input this is the digital input to alternate functions. in the figure, the signal is connected to the output of the schmitt trigger but before the synchronizer. unless the digital input is used as a clock source, the module with the alternate function will use its own synchronizer. aio analog input/output this is the analog input/output to/from alternate functions. the signal is connected directly to the pad, and can be used bi- directionally.
59 atmega8535(l) 2502k?avr?10/06 special function io register ? sfior ? bit 2 ? pud: pull-up disable when this bit is written to one, the pull-ups in the i/o ports are disabled even if the ddxn and portxn registers are configured to enable the pull-ups ({ddxn, portxn} = 0b01). see ?configuring the pin? on page 52 for more details about this feature. alternate functions of port a port a has an alternate function as analog input for the adc as shown in table 23. if some port a pins are configured as outputs, it is essential that these do not switch when a conversion is in progress. this might corrupt the result of the conversion. table 24 and table 25 relate the alternate functions of port a to the overriding signals shown in figure 26 on page 57. bit 7 6 5 4 3 2 1 0 adts2 adts1 adts0 ? acme pud psr2 psr10 sfior read/write r/w r/w r/w r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 23. port a pins alternate functions port pin alternate function pa7 adc7 (adc input channel 7) pa6 adc6 (adc input channel 6) pa5 adc5 (adc input channel 5) pa4 adc4 (adc input channel 4) pa3 adc3 (adc input channel 3) pa2 adc2 (adc input channel 2) pa1 adc1 (adc input channel 1) pa0 adc0 (adc input channel 0) table 24. overriding signals for alternate functions in pa7..pa4 signal name pa7/adc7 pa6 /adc6 pa5/adc5 pa4/adc4 puoe0000 puov0000 ddoe0000 ddov0000 pvoe0000 pvov0000 dieoe0000 dieov0000 di???? aio adc7 input adc6 input adc5 input adc4 input
60 atmega8535(l) 2502k?avr?10/06 alternate functions of port b the port b pins with alternate functions are shown in table 26. the alternate pin configuration is as follows: ? sck ? port b, bit 7 sck: master clock output, slave clock input pin for spi channel. when the spi is enabled as a slave, this pin is configured as an input regardless of the setting of ddb7. when the spi is enabled as a master, the da ta direction of this pin is controlled by ddb7. when the pin is forced by the spi to be an input, the pull-up can still be con- trolled by the portb7 bit. ? miso ? port b, bit 6 miso: master data input, slave data output pin for spi channel. when the spi is enabled as a master, this pin is configured as an input regardless of the setting of ddb6. when the spi is enabled as a slave, th e data direction of this pin is controlled by ddb6. when the pin is forced by the spi to be an input, the pull-up can still be con- trolled by the portb6 bit. table 25. overriding signals for alternate functions in pa3..pa0 signal name pa3/adc3 pa2 /adc2 pa1/adc1 pa0/adc0 puoe0000 puov0000 ddoe0000 ddov0000 pvoe0000 pvov0000 dieoe0000 dieov0000 di???? aio adc3 input adc2 input adc1 input adc0 input table 26. port b pins alternate functions port pin alternate functions pb7 sck (spi bus serial clock) pb6 miso (spi bus master input/slave output) pb5 mosi (spi bus master output/slave input) pb4 ss (spi slave select input) pb3 ain1 (analog comparator negative input) oc0 (timer/counter0 output compare match output) pb2 ain0 (analog comparator positive input) int2 (external interrupt 2 input) pb1 t1 (timer/counter1 external counter input) pb0 t0 (timer/counter0 external counter input) xck (usart external clock input/output)
61 atmega8535(l) 2502k?avr?10/06 ? mosi ? port b, bit 5 mosi: spi master data output, slave data input for spi channel. when the spi is enabled as a slave, this pin is configured as an input regardless of the setting of ddb5. when the spi is enabled as a master, the da ta direction of this pin is controlled by ddb5. when the pin is forced by the spi to be an input, the pull-up can still be con- trolled by the portb5 bit. ?ss ? port b, bit 4 ss : slave select input. when the spi is enabled as a slave, this pin is configured as an input regardless of the setting of ddb4. as a slave, the spi is activated when this pin is driven low. when the spi is enabled as a master , the data direction of this pin is con- trolled by ddb4. when the pin is forced by the spi to be an input, the pull-up can still be controlled by the portb4 bit. ? ain1/oc0 ? port b, bit 3 ain1, analog comparator negative input. configure the port pin as input with the inter- nal pull-up switched off to avoid the digital port function from interfering with the function of the analog comparator. oc0, output compare match output: the pb3 pin can serve as an external output for the timer/counter0 compare match. the pb3 pin has to be configured as an output (ddb3 set (one)) to serve this function. the oc0 pin is also the output pin for the pwm mode timer function. ? ain0/int2 ? port b, bit 2 ain0, analog comparator positive input. configure the port pin as input with the internal pull-up switched off to avoid the digital port function from interfering with the function of the analog comparator. int2, external interrupt source 2: the pb2 pin can serve as an external interrupt source to the mcu. ? t1 ? port b, bit 1 t1, timer/counter1 counter source. ? t0/xck ? port b, bit 0 t0, timer/counter0 counter source. xck, usart external clock. th e data direction register ( ddb0) controls whether the clock is output (ddb0 set) or input (ddb0 cleared). the xck pin is active only when the usart operates in synchronous mode. table 27 and table 28 relate the alternate functions of port b to the overriding signals shown in figure 26 on page 57. spi mstr input and spi slave output constitute the miso signal, while mosi is divide d into spi mstr output and spi slave input.
62 atmega8535(l) 2502k?avr?10/06 alternate functions of port c the port c pins with alternate functions are shown in table 29. the alternate pin configuration is as follows: ? tosc2 ? port c, bit 7 table 27. overriding signals for alternate functions in pb7..pb4 signal name pb7/sck pb6/miso pb5/mosi pb4/ss puoe spe ? mstr spe ? mstr spe ? mstr spe ? mstr puov portb7 ? pud portb6 ? pud portb5 ? pud portb4 ? pud ddoe spe ? mstr spe ? mstr spe ? mstr spe ? mstr ddov 0 0 0 0 pvoe spe ? mstr spe ? mstr spe ? mstr 0 pvov sck output spi slave output spi mstr output 0 dieoe 0 0 0 0 dieov 0 0 0 0 di sck input spi mstr input spi slave input spi ss aio ? ? ? ? table 28. overriding signals for alternate functions in pb3..pb0 signal name pb3/oc0/ain1 pb2/int2/ain0 pb1/t1 pb0/t0/xck puoe 0 0 0 0 puov 0 0 0 0 ddoe 0 0 0 0 ddov 0 0 0 0 pvoe oc0 enable 0 0 umsel pvov oc0 0 0 xck output dieoe 0 int2 enable 0 0 dieov 0 1 0 0 di ? int2 input t1 input xck input/ t0 input aio ain1 input ain0 input ? ? table 29. port c pins alternate functions port pin alternate function pc7 tosc2 (timer oscillator pin 2) pc6 tosc1 (timer oscillator pin 1) pc1 sda (two-wire serial bus data input/output line) pc0 scl (two-wire serial bus clock line)
63 atmega8535(l) 2502k?avr?10/06 tosc2, timer oscillator pin 2: when the as 2 bit in assr is set (one) to enable asyn- chronous clocking of timer/counter2, pin pc7 is disconnected from the port, and becomes the inverting output of the oscillator amplif ier. in this mode, a crystal oscillator is connected to this pin, and the pin can not be used as an i/o pin. ? tosc1 ? port c, bit 6 tosc1, timer oscillator pin 1: when the as 2 bit in assr is set (one) to enable asyn- chronous clocking of timer/counter2, pin pc6 is disconnected from the port, and becomes the input of the inverting oscillator amplifier. in this mode, a crystal oscillator is connected to this pin, and the pin can not be used as an i/o pin. ? sda ? port c, bit 1 sda, two-wire serial interface data: when the twen bit in twcr is set (one) to enable the two-wire serial interface, pin pc1 is disconnected from the port and becomes the serial data i/o pin for the two-wire serial interface. in this mode, there is a spike filter on the pin to suppress spikes shorter than 50 ns on the input signal, and the pin is driven by an open drain driver with slew-rate limitation. when this pin is used by the two-wire serial interfac e, the pull-up can still be co ntrolled by the portc1 bit. ? scl ? port c, bit 0 scl, two-wire serial interface clock: when the twen bit in twcr is set (one) to enable the two-wire serial interface, pin pc0 is disconnected from the port and becomes the serial clock i/o pin for the two-wire serial interface. in this mode, there is a spike filter on the pin to suppress spikes shorter than 50 ns on the input signal, and the pin is driven by an open drain driver with slew-rate limitation. when this pin is used by the two-wire serial interfac e, the pull-up can still be co ntrolled by the portc0 bit. table 30 and table 31 relate the alternate functions of port c to the overriding signals shown in figure 26 on page 57. table 30. overriding signals for alternate functions in pc7..pc6 signal name pc7/tosc2 pc6/tosc1 puoe as2 as2 puov 0 0 ddoe as2 as2 ddov 0 0 pvoe 0 0 pvov 0 0 dieoe as2 as2 dieov 0 0 di ? ? aio t/c2 osc output t/c2 osc input
64 atmega8535(l) 2502k?avr?10/06 note: 1. when enabled, the two-wire serial inte rface enables slew-rate controls on the output pins pc0 and pc1. this is not shown in the figure. in addition, spike filters are con- nected between the aio outputs shown in the port figure and the digital logic of the twi module. alternate functions of port d the port d pins with alternate functions are shown in table 32. the alternate pin configuration is as follows: ? oc2 ? port d, bit 7 oc2, timer/counter2 output compare match output: the pd7 pin can serve as an external output for the timer/counter2 output compare. the pin has to be configured as an output (ddd7 set (one)) to serve this function. th e oc2 pin is also the output pin for the pwm mode timer function. ? icp1 ? port d, bit 6 icp1 ? input capture pin: the pd6 pin can act as an input capture pin for timer/counter1. ? oc1a ? port d, bit 5 oc1a, output compare match a output: the pd5 pin can serve as an external output for the timer/counter1 output compare a. the pin has to be configured as an output table 31. overriding signals for alternate functions in pc1..pc0 (1) signal name pc1/sda pc0/scl puoe twen twen puov portc1 ? pud portc0 ? pud ddoe twen twen ddov sda_out scl_out pvoe twen twen pvov 0 0 dieoe 0 0 dieov 0 0 di ? ? aio sda input scl input table 32. port d pins alternate functions port pin alternate function pd7 oc2 (timer/counter2 output compare match output) pd6 icp1 (timer/counter 1 input capture pin) pd5 oc1a (timer/counter1 output compare a match output) pd4 oc1b (timer/counter1 output compare b match output) pd3 int1 (external interrupt 1 input) pd2 int0 (external interrupt 0 input) pd1 txd (usart output pin) pd0 rxd (usart input pin)
65 atmega8535(l) 2502k?avr?10/06 (ddd5 set (one)) to serve this function. the oc1a pin is also the output pin for the pwm mode timer function. ? oc1b ? port d, bit 4 oc1b, output compare match b output: the pd4 pin can serve as an external output for the timer/counter1 output compare b. the pin has to be configured as an output (ddd4 set (one)) to serve this function. the oc1b pin is also the output pin for the pwm mode timer function. ? int1 ? port d, bit 3 int1, external interrupt source 1: the pd3 pin can serve as an external interrupt source. ? int0 ? port d, bit 2 int0, external interrupt source 0: the pd2 pin can serve as an external interrupt source. ?txd ? port d, bit 1 txd, transmit data (data output pin for the usart). when the usart transmitter is enabled, this pin is configured as an output regardless of the value of ddd1. ? rxd ? port d, bit 0 rxd, receive data (data input pin for the usart). when the usart receiver is enabled this pin is configured as an inpu t regardless of the value of ddd0. when the usart forces this pin to be an input, the pull-up can still be controlled by the portd0 bit. table 33 and table 34 relate the alternate functions of port d to the overriding signals shown in figure 26 on page 57. table 33. overriding signals for alternate functions pd7..pd4 signal name pd7/oc2 pd6/icp1 pd5/oc1a pd4/oc1b puoe 0 0 0 0 puov 0 0 0 0 ddoe 0 0 0 0 ddov 0 0 0 0 pvoe oc2 enable 0 oc1a enable oc1b enable pvov oc2 0 oc1a oc1b dieoe 0 0 0 0 dieov 0 0 0 0 di ? icp1 input ? ? aio ? ? ? ?
66 atmega8535(l) 2502k?avr?10/06 register description for i/o-ports port a data register ? porta port a data direction register ? ddra port a input pins address ? pina port b data register ? portb port b data direction register ? ddrb table 34. overriding signals for alternate functions in pd3..pd0 signal name pd3/int1 pd 2/int0 pd1/txd pd0/rxd puoe 0 0 txen rxen puov 0 0 0 portd0 ? pud ddoe 0 0 txen rxen ddov 0 0 1 0 pvoe 0 0 txen 0 pvov 0 0 txd 0 dieoe int1 enable int0 enable 0 0 dieov1100 di int1 input int0 input ? rxd aio???? bit 76543210 porta7 porta6 porta5 porta4 porta3 porta2 porta1 porta0 porta read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 dda7 dda6 dda5 dda4 dda3 dda2 dda1 dda0 ddra read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 pina7 pina6 pina5 pina4 pi na3 pina2 pina1 pina0 pina read/writerrrrrrrr initial value n/a n/a n/a n/a n/a n/a n/a n/a bit 76543210 portb7 portb6 portb5 portb4 portb3 portb2 portb1 portb0 portb read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 00000000 bit 76543210 ddb7 ddb6 ddb5 ddb4 ddb3 ddb2 ddb1 ddb0 ddrb read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
67 atmega8535(l) 2502k?avr?10/06 port b input pins address ? pinb port c data register ? portc port c data direction register ? ddrc port c input pins address ? pinc port d data register ? portd port d data direction register ? ddrd port d input pins address ? pind bit 76543210 pinb7 pinb6 pinb5 pinb4 pi nb3 pinb2 pinb1 pinb0 pinb read/writerrrrrrrr initial value n/a n/a n/a n/a n/a n/a n/a n/a bit 76543210 portc7 portc6 portc5 portc4 portc3 portc2 portc1 portc0 portc read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ddc7 ddc6 ddc5 ddc4 ddc3 ddc2 ddc1 ddc0 ddrc read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 pinc7 pinc6 pinc5 pinc4 pi nc3 pinc2 pinc1 pinc0 pinc read/writerrrrrrrr initial value n/a n/a n/a n/a n/a n/a n/a n/a bit 76543210 portd7 portd6 portd5 portd4 portd3 portd2 portd1 portd0 portd read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ddd7 ddd6 ddd5 ddd4 ddd3 ddd2 ddd1 ddd0 ddrd read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 pind7 pind6 pind5 pind4 pi nd3 pind2 pind1 pind0 pind read/writerrrrrrrr initial value n/a n/a n/a n/a n/a n/a n/a n/a
68 atmega8535(l) 2502k?avr?10/06 external interrupts the external interrupts are triggered by t he int0, int1, and int2 pins. observe that, if enabled, the interrupts will trigger even if the int0..2 pins are configured as outputs. this feature provides a way of generating a software interrupt. the external interrupts can be triggered by a falling or rising edge or a low level (int2 is only an edge triggered interrupt). this is set up as indicated in th e specification for the mcu control register ? mcucr and mcu control and status regist er ? mcucsr. when the external inter- rupt is enabled and is configured as level tr iggered (only int0/int1), the interrupt will trigger as long as the pin is held low. note that recognition of fallin g or rising edge inter- rupts on int0 and int1 requires the pres ence of an i/o clock, described in ?clock systems and their distribution? on page 24. low level interrupts on int0/int1 and the edge interrupt on int2 are detected asynchronously. this implies that these interrupts can be used for waking the part also from sleep modes other than idle mode. the i/o clock is halted in all sleep modes except idle mode. note that if a level triggered interrupt is used for wake-up from power-down mode, the changed level must be held for some time to wake up the mcu. this makes the mcu less sensitive to noise. the changed level is sampled twic e by the watchdog oscillator clock. the period of the watchdog oscillator is 1 s (nominal) at 5.0v and 25 c. the frequency of the watchdog osc illator is voltage dependent as shown in ?electrical char- acteristics? on page 255. the mcu will wake up if the input has the required level during this sampling or if it is held until the end of the start-up time. the start-up time is defined by the sut fuses as described in ?system clock and clock options? on page 24. if the level is sampled twice by the watchdog oscillator clock but disappears before the end of the start-up time, the mcu will still wake up, but no interrupt will be generated. the required level must be held long enough for the mcu to complete the wake up to trigger the level interrupt. mcu control register ? mcucr the mcu control register contains control bits for interrupt sense control and general mcu functions. ? bit 3, 2 ? isc11, isc10: interrupt sense control 1 bit 1 and bit 0 the external interrupt 1 is activated by the external pin int1 if the sreg i-bit and the corresponding interrupt mask in the gicr are set. the level and edges on the external int1 pin that activate the interrupt are defined in table 35. the value on the int1 pin is sampled before detecting edges. if edge or toggle interrupt is selected, pulses that last longer than one clock period will generate an interrupt. shorter pu lses are not guaran- teed to generate an interrupt. if low level in terrupt is selected, the low level must be held until the completion of the currently executing instruction to generate an interrupt. ? bit 1, 0 ? isc01, isc00: interrupt sense control 0 bit 1 and bit 0 bit 76543210 sm2 se sm1 sm0 isc11 isc10 isc01 isc00 mcucr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 table 35. interrupt 1 sense control isc11 isc10 description 0 0 the low level of int1 generates an interrupt request. 0 1 any logical change on int1 generates an interrupt request. 1 0 the falling edge of int1 generates an interrupt request. 1 1 the rising edge of int1 generates an interrupt request.
69 atmega8535(l) 2502k?avr?10/06 the external interrupt 0 is activated by the external pin int0 if the sreg i-flag and the corresponding interrupt mask are set. the level and edges on the external int0 pin that activate the interrupt are defined in tabl e 36. the value on the int0 pin is sampled before detecting edges. if edge or toggle interrupt is selected, pulses that last longer than one clock period will generate an interrupt. shorter pulses are not guaranteed to generate an interrupt. if low level interrupt is selected, the low level must be held until the completion of the currently executing instruction to generate an interrupt. mcu control and status register ? mcucsr ? bit 6 ? isc2: interrupt sense control 2 the asynchronous external interrupt 2 is activated by the external pin int2 if the sreg i-bit and the corresponding interrupt mask in gicr are set. if isc2 is written to zero, a falling edge on int2 activates the interrupt. if isc2 is written to one, a rising edge on int2 activates the interrupt. edges on int2 are registered asynchronously. pulses on int2 wider than the minimum pulse width given in table 37 will generate an interrupt. shorter pulses are not guaranteed to generate an interrupt. when changing the isc2 bit, an interrupt can occur. therefore, it is recommended to first disable int2 by clearing its interrupt enable bit in the gicr register. then, the isc2 bit can be changed. finally, the int2 interrupt flag should be cleared by writing a logical one to its interrupt flag bit (intf2) in the gifr register before the interrupt is re-enabled. general interrupt control register ? gicr ? bit 7 ? int1: external interrupt request 1 enable when the int1 bit is set (one) and the i-bit in the status register (sreg) is set (one), the external pin interrupt is enabled. the interrupt sense control1 bits 1/0 (isc11 and isc10) in the mcu general control regi ster (mcucr) define whether the external interrupt is activated on the rising and/or falling edge of the int1 pin or level sensed. activity on the pin will cause an interrupt request even if int1 is configured as an output. table 36. interrupt 0 sense control isc01 isc00 description 0 0 the low level of int0 generates an interrupt request. 0 1 any logical change on int0 generates an interrupt request. 1 0 the falling edge of int0 generates an interrupt request. 1 1 the rising edge of int0 generates an interrupt request. bit 76543210 ?isc2 ? ? wdrf borf extrf porf mcucsr read/write r/w r/w r r/w r/w r/w r/w r/w initial value 0 0 0 see bit description table 37. asynchronous external interrupt characteristics symbol parameter min typ max units t int minimum pulse width for asynchronous external interrupt 50 ns bit 76543210 int1 int0 int2 ? ? ? ivsel ivce gicr read/write r/w r/w r/w r r r r/w r/w initial value 0 0 0 0 0 0 0 0
70 atmega8535(l) 2502k?avr?10/06 the corresponding interrupt of external inte rrupt request 1 is executed from the int1 interrupt vector. ? bit 6 ? int0: external interrupt request 0 enable when the int0 bit is set (one) and the i-bit in the status register (sreg) is set (one), the external pin interrupt is enabled. the interrupt sense control0 bits 1/0 (isc01 and isc00) in the mcu general control regi ster (mcucr) define whether the external interrupt is activated on rising and/or falling edge of the int0 pin or level sensed. activity on the pin will cause an interrupt request even if int0 is configured as an output. the corresponding interrupt of external interrupt request 0 is executed from the int0 inter- rupt vector. ? bit 5 ? int2: external interrupt request 2 enable when the int2 bit is set (one) and the i-bit in the status register (sreg) is set (one), the external pin interrupt is enabled. the inte rrupt sense control2 bit (isc2) in the mcu control and status register (mcucsr) defines whether the external interrupt is acti- vated on the rising or falling edge of the in t2 pin. activity on the pin will cause an interrupt request even if int2 is configured as an output. the corresponding interrupt of external interrupt reques t 2 is executed from the int2 interrupt vector. general interrupt flag register ? gifr ? bit 7 ? intf1: external interrupt flag 1 when an edge or logic change on the int1 pin triggers an interrupt request, intf1 becomes set (one). if the i-bit in sreg and the int1 bit in gicr are set (one), the mcu will jump to the corresponding interrupt vector. the flag is cleared when the interrupt routine is executed. alternatively, the flag can be cleared by writing a logical one to it. this flag is always cleared when int1 is configured as a level interrupt. ? bit 6 ? intf0: external interrupt flag 0 when an edge or logic change on the int0 pin triggers an interrupt request, intf0 becomes set (one). if the i-bit in sreg and the int0 bit in gicr are set (one), the mcu will jump to the corresponding interrupt vector. the flag is cleared when the interrupt routine is executed. alternatively, the flag can be cleared by writing a logical one to it. this flag is always cleared when int0 is configured as a level interrupt. ? bit 5 ? intf2: external interrupt flag 2 when an event on the int2 pin triggers an interrupt request, intf2 becomes set (one). if the i-bit in sreg and the int2 bit in gi cr are set (one), the mcu will jump to the cor- responding interrupt vector. the flag is cleared when the interrupt routine is executed. alternatively, the flag can be cleared by writing a logical one to it. note that when enter- ing some sleep modes with the int2 interrupt disabled, the input buffer on this pin will be disabled. this may cause a logic change in internal si gnals which will set the intf2 flag. see ?digital input enable and sleep modes? on page 55 for more information. bit 76543210 intf1 intf0 intf2 ? ? ? ? ?gifr read/write r/w r/w r/w r r r r r initial value 0 0 0 0 0 0 0 0
71 atmega8535(l) 2502k?avr?10/06 8-bit timer/counter0 with pwm timer/counter0 is a general purpose, single channel, 8-bit timer/counter module. the main features are: ? single channel counter ? clear timer on compar e match (auto reload) ? glitch-free, phase correct pu lse width modulator (pwm) ? frequency generator ? external event counter ? 10-bit clock prescaler ? overflow and compare match in terrupt sources (tov0 and ocf0) overview a simplified block diagram of the 8-bit time r/counter is shown in figure 27. for the actual placement of i/o pins, refer to ?pinout atmega8535? on page 2. cpu accessible i/o registers, including i/o bits and i/o pins , are shown in bold. the device-specific i/o register and bit locations are listed in the ?8-bit timer/counter register description? on page 83. figure 27. 8-bit timer/counter block diagram registers the timer/counter (tcnt0) and output compare register (ocr0) are 8-bit registers. interrupt request (abbreviated to int.req. in the figure) signals are all visible in the timer interrupt flag register (tifr). all interrupts are individually masked with the timer interrupt mask register (timsk). tifr a nd timsk are not shown in the figure since these registers are shared by other timer units. the timer/counter can be clocked internally, via the prescaler, or by an external clock source on the t0 pin. the clock select logic block controls which clock source and edge the timer/counter uses to increment (or decrement) its value. the timer/counter is inactive when no cloc k source is selected. the output from the clock select logic is referred to as the timer clock (clk t0 ). timer/counter data b u s = tcntn waveform generation ocn = 0 control logic = 0xff bottom count clear direction tovn (int.req.) ocrn tccrn clock select tn edge detector ( from prescaler ) clk tn top ocn (int.req.)
72 atmega8535(l) 2502k?avr?10/06 the double buffered output compare register (ocr0) is compared with the timer/counter value at all times. the result of the compare can be used by the wave- form generator to generate a pwm or variable frequency output on the output compare pin (oc0). see ?output compare unit? on page 73. for details. the compare match event will also set the compare flag (ocf0) which can be used to generate an output compare interrupt request. definitions many register and bit references in this document are written in general form. a lower case ?n? replaces the timer/counter number, in this case 0. however, when using the register or bit defines in a program, the precise form must be used, i.e., tcnt0 for accessing timer/counter0 co unter value and so on. the definitions in table 38 are also used extensively throughout the document. timer/counter clock sources the timer/counter can be clocked by an intern al or an external clock source. the clock source is selected by the clock select logic which is controlled by the clock select (cs02:0) bits located in the timer/counter control register (tccr0). for details on clock sources and pre scaler, see ?timer/counter0 and timer/counter1 prescalers? on page 87. counter unit the main part of the 8-bit timer/counter is the programmable bi-directional counter unit. figure 28 shows a block diagram of the counter and its surroundings. figure 28. counter unit block diagram signal description (internal signals): count increment or decrement tcnt0 by 1. direction select between increment and decrement. clear clear tcnt0 (set all bits to zero). clk t n timer/counter clock, referred to as clk t0 in the following. table 38. definitions bottom the counter reaches the bottom when it becomes 0x00. max the counter reaches its maximum when it becomes 0xff (decimal 255). top the counter reaches the top when it becomes equal to the highest value in the count sequence. the top value can be assigned to be the fixed value 0xff (max) or the value stored in the ocr0 register. the assignment is dependent on the mode of operation. data b u s tcntn control logic count tovn (int.req.) clock select top tn edge detector ( from prescaler ) clk tn bottom direction clear
73 atmega8535(l) 2502k?avr?10/06 top signalize that tcnt0 has reached maximum value. bottom signalize that tcnt0 has reached minimum value (zero). depending of the mode of operation used, the counter is cleared, incremented, or dec- remented at each timer clock (clk t0 ). clk t0 can be generated from an external or internal clock source, selected by the clock select bits (cs02:0). when no clock source is selected (cs02:0 = 0) the timer is stopped. however, the tcnt0 value can be accessed by the cpu, regardless of whether clk t0 is present or not. a cpu write overrides (has priority over) all counter clear or count operations. the counting sequence is determined by the setting of the wgm01 and wgm00 bits located in the timer/counter control register (tccr0). there are close connections between how the counter behaves (counts) and how waveforms are generated on the output compare output oc0. for more details about advanced counting sequences and waveform generation, see ?modes of operation? on page 76. the timer/counter overflow flag (tov0) is set according to the mode of operation selected by the wgm01:0 bits. tov0 can be used for generating a cpu interrupt. output compare unit the 8-bit comparator continuously compares tcnt0 with the output compare register (ocr0). whenever tcnt0 equals ocr0, the comparator signals a match. a match will set the output compare flag (ocf0) at the next timer clock cycle. if enabled (ocie0 = 1 and global interrupt flag in sreg is set), the output compare flag generates an out- put compare interrupt. the ocf0 flag is automatically cleared when the interrupt is executed. alternatively, the ocf0 flag can be cleared by software by writing a logical one to its i/o bit location. the waveform generator uses the match signal to generate an output according to operating mode set by the wgm01:0 bits and compare output mode (com01:0) bits. the max and bottom signals are used by the waveform genera- tor for handling the special cases of the extreme values in some modes of operation (see ?modes of operation? on page 76.). figure 29 shows a block diagram of the output compare unit. figure 29. output compare unit, block diagram ocfn (int.req.) = (8-bit comparator ) ocrn ocn data b u s tcntn wgmn1:0 waveform generator top focn comn1:0 bottom
74 atmega8535(l) 2502k?avr?10/06 the ocr0 register is double buffered when using any of the pulse width modulation (pwm) modes. for the normal and clear timer on compare (ctc) modes of operation, the double buffering is disabled. the double buffering synchronizes the update of the ocr0 compare register to either top or bottom of the counting sequence. the synchro- nization prevents the occurrence of odd-l ength, non-symmetrical pwm pulses, thereby making the output glitch-free. the ocr0 register access ma y seem complex, but this is not the case. when the dou- ble buffering is enabled, the cpu has access to the ocr0 buffer register, and if double buffering is disabled the cp u will access the ocr0 directly. force output compare in non-pwm waveform generation modes, the match output of the comparator can be forced by writing a one to the force output compare (foc0) bit. forcing compare match will not set the ocf0 flag or reload/c lear the timer, but the oc0 pin will be updated as if a real compare match had occurred (the com01:0 bits settings define whether the oc0 pin is set, cleared or toggled). compare match blocking by tcnt0 write all cpu write operations to the tcnt0 register will block any compare match that occur in the next timer clock cycle, even w hen the timer is stopped. this feature allows ocr0 to be initialized to th e same value as tcnt0 without triggering an interrupt when the timer/counter clock is enabled. using the output compare unit since writing tcnt0 in any mode of operat ion will block all compare matches for one timer clock cycle, there are risks involved when changing tcnt0 when using the output compare channel, independently of whether the timer/counter is running or not. if the value written to tcnt0 equa ls the ocr0 value, the compare match will be missed, resulting in incorrect waveform generation . similarly, do not write the tcnt0 value equal to bottom when the counter is down-counting. the setup of the oc0 should be performed before setting the data direction register for the port pin to output. the easiest way of setting the oc0 value is to use the force output compare (foc0) strobe bits in normal mode. the oc0 register keeps its value even when changing between waveform generation modes. be aware that the com01:0 bits are not double buffered together with the compare value. changing the com01:0 bits will take effect immediately.
75 atmega8535(l) 2502k?avr?10/06 compare match output unit the compare output mode (com01:0) bits have two functions. the waveform genera- tor uses the com01:0 bits for defining the output compare (oc0) state at the next compare match. also, the com01:0 bits control the oc0 pin output source. figure 30 shows a simplified schematic of the logic affected by the com01:0 bit setting. the i/o registers, i/o bits, and i/o pins in the figur e are shown in bold. only the parts of the general i/o port control registers (ddr and port) that are affected by the com01:0 bits are shown. when referring to the oc0 st ate, the reference is for the internal oc0 register, not the oc0 pin. if a system reset occur, the oc0 register is reset to ?0?. figure 30. compare match output unit, schematic the general i/o port function is overridden by the output compare (oc0) from the waveform generator if either of the com01:0 bits are set. however, the oc0 pin direc- tion (input or output) is still controlled by t he data direction register (ddr) for the port pin. the data direction register bit for the oc0 pin (ddr_oc0) must be set as output before the oc0 value is visible on the pi n. the port override function is independent of the waveform generation mode. the design of the output compare pin logic al lows initialization of the oc0 state before the output is enabled. note that some com01:0 bit settings are reserved for certain modes of operation. see ?8-bit timer/counter register description? on page 83. compare output mode and waveform generation the waveform generator uses the com01:0 bits differently in normal, ctc, and pwm modes. for all modes, setting the com01:0 = 0 tells the waveform generator that no action on the oc0 register is to be performed on the next compare match. for com- pare output actions in the non-pwm modes refer to table 40 on page 84. for fast pwm mode, refer to table 41 on page 84, and for phase correct pwm refer to table 42 on page 84. a change of the com01: 0 bits state will have ef fect at the first co mpare match after the bits are written. for non-pwm modes, the action can be forced to have immediate effect by using the foc0 strobe bits. port ddr dq dq ocn pin ocn dq waveform generator comn1 comn0 0 1 data b u s focn clk i/o
76 atmega8535(l) 2502k?avr?10/06 modes of operation the mode of operation, i.e., the behavior of the timer/counter and the output compare pins, is defined by the combination of the waveform generation mode (wgm01:0) and compare output mode (com01:0) bits. the compare output mode bits do not affect the counting sequence, while the waveform generation mode bits do. the com01:0 bits control whether the pwm output generated should be inverted or not (inverted or non-inverted pwm). for non-pwm modes the com01:0 bits control whether the output should be set, cleared, or toggled at a compare match (see ?compare match output unit? on page 75.). for detailed timing information refer to figure 34, figure 35, figure 36, and figure 37 in ?timer/counter timing diagrams? on page 80. normal mode the simplest mode of operation is the normal mode (wgm01:0 = 0). in this mode the counting direction is always up (incrementing), and no counter clear is performed. the counter simply overruns when it passes its maximum 8-bit value (top = 0xff) and then restarts from the bottom (0x00). in normal operation the timer/counter overflow flag ( tov 0) will be set in the same timer clock cycle as the tcnt0 becomes zero. the tov0 flag in this case behaves like a ninth bit, except that it is only set, not cleared. however, combined with the timer overflow interrupt that automatically clears the tov0 flag, the timer resolution can be increased by software. there are no special cases to consider in the normal mode, a new counter value can be written anytime. the output compare unit can be used to generate interrupts at some given time. using the output compare to generate waveforms in normal mode is not recommended, since this will occupy too much of the cpu time. clear timer on compare match (ctc) mode in clear timer on compare or ctc mode (wgm01:0 = 2), the ocr0 register is used to manipulate the counter resolution. in ctc mo de the counter is cleared to zero when the counter value (tcnt0) matches the ocr0. the ocr0 defines the top value for the counter, hence also its resolution. this mode allows greater control of the compare match output frequency. it also simplifies th e operation of counting external events. the timing diagram for the ctc mode is shown in figure 31. the counter value (tcnt0) increases until a compare match occurs between tcnt0 and ocr0, and then counter (tcnt0) is cleared. figure 31. ctc mode, timing diagram an interrupt can be generated each time the counter value reaches the top value by using the ocf0 flag. if the interrupt is enabled, the interrupt handler routine can be used for updating the top value. however, changing top to a value close to bottom tcntn ocn (toggle) ocn interrupt flag set 1 4 period 2 3 (comn1:0 = 1)
77 atmega8535(l) 2502k?avr?10/06 when the counter is running with none or a low prescaler value must be done with care since the ctc mode does not have the double buffering feature. if the new value written to ocr0 is lower than the current value of tcnt0, the counter will miss the compare match. the counter will then have to count to its maxi mum value (0xff) and wrap around starting at 0x00 before the compare match can occur. for generating a waveform output in ctc mode, the oc0 output can be set to toggle its logical level on each compare match by setting the compare output mode bits to toggle mode (com01:0 = 1). the oc0 value will not be visible on the port pin unless the data direction for the pin is set to output. the wave form generated will have a maximum fre- quency of f oc0 = f clk_i/o /2 when ocr0 is set to zero (0x00). the waveform frequency is defined by the following equation: the ? n? variable represents the prescale factor (1, 8, 64, 256, or 1024). as for the normal mode of operation, the tov0 flag is set in the same timer clock cycle that the counter counts from max to 0x00. fast pwm mode the fast pulse width modulation or fast pwm mode (wgm01:0 = 3) provides a high fre- quency pwm waveform generation option. the fast pwm differs from the other pwm option by its single-slope operation. the counter counts from bottom to max then restarts from bottom. in non-inverting compare output mode, the output compare (oc0) is cleared on the compare match between tcnt0 and ocr0, and set at bot- tom. in inverting compare output mode, the output is set on compare match and cleared at bottom. due to the single-slope operation, the operating frequency of the fast pwm mode can be twice as high as the phase correct pwm mode that use dual- slope operation. this high frequency makes the fast pwm mode well suited for power regulation, rectification, and dac applicat ions. high frequency allows physically small sized external components (coils, capacitors), and therefore reduces total system cost. in fast pwm mode, the counter is incremented until the counter value matches the max value. the counter is then cleared at the following timer clock cycle. the timing diagram for the fast pwm mode is shown in figure 32. the tcnt0 value is in the timing diagram shown as a histogram for illustrating the single-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt0 slopes represent compare matches between ocr0 and tcnt0. f ocn f clk_i/o 2 n 1 ocrn + () ?? ---------------------------------------------- - =
78 atmega8535(l) 2502k?avr?10/06 figure 32. fast pwm mode, timing diagram the timer/counter overflow flag (tov0) is set each time the counter reaches max. if the interrupt is enabled, the interrupt handler routine can be used for updating the com- pare value. in fast pwm mode, the compare unit allows generation of pwm waveforms on the oc0 pin. setting the com01:0 bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the com01:0 to three (see table 41 on page 84). the actual oc0 value will on ly be visible on the port pin if the data direction for the port pin is set as output. the pwm waveform is generated by setting (or clearing) the oc0 register at the compare match between ocr0 and tcnt0, and clearing (or set- ting) the oc0 register at the timer clock cycle the counter is cleared (changes from max to bottom). the pwm frequency for the output can be calculated by the following equation: the ? n? variable represents the prescale factor (1, 8, 64, 256, or 1024). the extreme values for the ocr0 register represents special cases when generating a pwm waveform output in the fast pwm mode. if the ocr0 is set equal to bottom, the output will be a narrow spike for each max+1 timer clock c ycle. setting the ocr0 equal to max will result in a constantly high or low output (depen ding on the pola rity of the out- put set by the com01:0 bits). a frequency (with 50% duty cycle) waveform output in fast pwm mode can be achieved by setting oc0 to toggle its logical level on each compare match (com01:0 = 1). the waveform generated will have a maximum frequency of f oc0 = f clk_i/o /2 when ocr0 is set to zero. this feature is similar to the oc0 toggle in ctc mode, except the double buffer feature of the output compare unit is enabled in the fast pwm mode. tcntn ocrn update and tovn interrupt flag set 1 period 2 3 ocn ocn (comn1:0 = 2) (comn1:0 = 3) ocrn interrupt flag set 4 5 6 7 f ocnpwm f clk_i/o n 256 ? ------------------ =
79 atmega8535(l) 2502k?avr?10/06 phase correct pwm mode the phase correct pwm mode (wgm01:0 = 1) provides a high resolution phase correct pwm waveform generation option. the phase correct pwm mode is based on a dual- slope operation. the counter counts repeatedly from bottom to max and then from max to bottom. in non-inverting compare output mode, the output compare (oc0) is cleared on the compare match between tcnt0 and ocr0 while up-counting, and set on the compare match while down-counting. in inverting output compare mode, the operation is inverted. the dual-slope operation has lower maximum operation frequency than single slope operation. however, due to the symmetric feature of the dual-slope pwm modes, these modes are preferred for motor control applications. the pwm resolution for the phase correct pwm mode is fixed to eight bits. in phase correct pwm mode the counter is incremented until the counter value matches max. when the counter reaches max, it change s the count direction. the tcnt0 value will be equal to max for one timer clock cycle. the timing diagram for the phase correct pwm mode is shown on figure 33. the tcnt0 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. the diagra m includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt0 slopes repre- sent compare matches between ocr0 and tcnt0. figure 33. phase correct pwm mode, timing diagram the timer/counter overflow flag (tov0) is set each time the counter reaches bot- tom. the interrupt flag can be used to generate an interrupt each time the counter reaches the bottom value. in phase correct pwm mode, the compare unit allows generation of pwm waveforms on the oc0 pin. setting the com01:0 bits to two will produce a non-inverted pwm. an inverted pwm output can be generated by setting the com01:0 to three (see table 42 on page 84). the actual oc0 value will only be visible on the port pin if the data direction for the port pin is set as output. the pwm waveform is generated by clearing (or setting) the oc0 register at the compare match between ocr0 and tcnt0 when the counter increments, and setting (or clearing) the oc0 register at compare match between tovn interrupt flag set ocn interrupt flag set 1 2 3 tcntn period ocn ocn (comn1:0 = 2) (comn1:0 = 3) ocrn update
80 atmega8535(l) 2502k?avr?10/06 ocr0 and tcnt0 when the counter decrements. the pwm frequency for the output when using phase correct pwm can be calculated by the following equation: the ? n ? variable represents the prescale factor (1, 8, 64, 256, or 1024). the extreme values for the ocr0 register represent special cases when generating a pwm waveform output in the phase correct pwm mode. if the ocr0 is set equal to bottom, the output will be cont inuously low and if set e qual to max the output will be continuously high for non-inverted pwm mode. for inverted pw m the output will have the opposite logic values. at the very start of period 2 in figure 33 ocn has a transition from high to low even though there is no compare match. the point of this transition is to guarantee symmetry around bottom. there are two cases that give a transition without compare match. ? ocr0 changes its value from max, like in figure 33. when the ocr0 value is max the ocn pin value is the same as the result of a down-counting compare match. to ensure symmetry around bottom the ocn value at max must correspond to the result of an up-counting compare match. ? the timer starts counting from a value higher than the one in ocr0, and for that reason misses the compare match and hence the ocn change that would have happened on the way up. timer/counter timing diagrams the timer/counter is a synchronous design and the timer clock (clk t0 ) is therefore shown as a clock enable signal in the followi ng figures. the figures include information on when interrupt flags are set. figure 34 c ontains timing data for basic timer/counter operation. the figure shows the count sequence close to the max value in all modes other than phase correct pwm mode. figure 34. timer/counter timing diagram, no prescaling figure 35 shows the same timing data, but with the prescaler enabled. f ocnpcpwm f clk_i/o n 510 ? ------------------ = clk tn (clk i/o /1) tovn clk i/o tcntn max - 1 max bottom bottom + 1
81 atmega8535(l) 2502k?avr?10/06 figure 35. timer/counter timing diagram, with prescaler (f clk_i/o /8) figure 36 shows the setting of ocf0 in all modes except ctc mode. figure 36. timer/counter timing diagram, setting of ocf0, with prescaler (f clk_i/o /8) figure 37 shows the setting of ocf0 and the clearing of tcnt0 in ctc mode. tovn tcntn max - 1 max bottom bottom + 1 clk i/o clk tn (clk i/o /8) ocfn ocrn tcntn ocrn value ocrn - 1 ocrn ocrn + 1 ocrn + 2 clk i/o clk tn (clk i/o /8)
82 atmega8535(l) 2502k?avr?10/06 figure 37. timer/counter timing diagram, clear timer on compare match mode, with prescaler (f clk_i/o /8) ocfn ocrn tcntn (ctc) top top - 1 top bottom bottom + 1 clk i/o clk tn (clk i/o /8)
83 atmega8535(l) 2502k?avr?10/06 8-bit timer/counter register description timer/counter control register ? tccr0 ? bit 7 ? foc0: force output compare the foc0 bit is only active when the wgm00 bit specifies a non-pwm mode. however, for ensuring compatibility with fu ture devices, this bit must be set to zero when tccr0 is written when operating in pwm mode. when writing a logical one to the foc0 bit, an immediate compare match is forced on the waveform generation unit. the oc0 output is changed according to its com01:0 bits setting. note that the foc0 bit is implemented as a strobe. therefore it is the value present in the com01:0 bits that determines the effect of the forced compare. a foc0 strobe will not generate any interr upt, nor will it clear the timer in ctc mode using ocr0 as top. the foc0 bit is always read as zero. ? bit 6, 3 ? wgm01:0: waveform generation mode these bits control the counting sequence of the counter, the source for the maximum (top) counter value, and what type of waveform generation to be used. modes of oper- ation supported by the timer/counter unit are: normal mode, clear timer on compare match (ctc) mode, and two types of pulse width modulation (pwm) modes. see table 39 and ?modes of operation? on page 76. note: 1. the ctc0 and pwm0 bit definition names are now obsolete. use the wgm01:0 def- initions. however, the functionality and loca tion of these bits are compatible with previous versions of the timer. ? bit 5:4 ? com01:0: compare match output mode these bits control the output compare pin (oc0) behavior. if one or both of the com01:0 bits are set, the oc0 output overrides the normal port functionality of the i/o pin it is connected to. however, note that t he data direction register (ddr) bit corre- sponding to the oc0 pin must be set in order to enable the output driver. bit 76543210 foc0 wgm00 com01 com00 wgm01 cs02 cs01 cs00 tccr0 read/write w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 39. waveform generation mode bit description (1) mode wgm01 (ctc0) wgm00 (pwm0) mode of operation top update of ocr0 tov0 flag set on 0 0 0 normal 0xff immediate max 1 0 1 pwm, phase correct 0xff top bottom 2 1 0 ctc ocr0 immediate max 31 1fast pwm 0xffbottommax
84 atmega8535(l) 2502k?avr?10/06 when oc0 is connected to the pin, the function of the com01:0 bits depends on the wgm01:0 bit setting. table 40 shows the com01:0 bit functionality when the wgm01:0 bits are set to a normal or ctc mode (non-pwm). table 41 shows the com01:0 bit functionality when the wgm01:0 bits are set to fast pwm mode. note: 1. a special case occurs when ocr0 equals top and com01 is set. in this case, the compare match is ignored, but the set or clear is done at top. see ?fast pwm mode? on page 77 for more details. table 42 shows the com01:0 bit functionality when the wgm01:0 bits are set to phase correct pwm mode. note: 1. a special case occurs when ocr0 equals top and com01 is set. in this case, the compare match is ignored, but the set or clear is done at top. see ?phase correct pwm mode? on page 79 for more details. table 40. compare output mode, non-pwm mode com01 com00 description 0 0 normal port operation, oc0 disconnected. 0 1 toggle oc0 on compare match 1 0 clear oc0 on compare match 1 1 set oc0 on compare match table 41. compare output mode, fast pwm mode (1) com01 com00 description 0 0 normal port operation, oc0 disconnected. 01reserved 1 0 clear oc0 on compare match, set oc0 at top (non-inverting). 1 1 set oc0 on compare match, clear oc0 at top (inverting) table 42. compare output mode, phase correct pwm mode (1) com01 com00 description 0 0 normal port operation, oc0 disconnected. 01reserved 1 0 clear oc0 on compare match when up-counting. set oc0 on compare match when down-counting. 1 1 set oc0 on compare match when up-counting. clear oc0 on compare match when down-counting.
85 atmega8535(l) 2502k?avr?10/06 ? bit 2:0 ? cs02:0: clock select the three clock select bits select the cloc k source to be used by the timer/counter. if external pin modes are used for the timer/counter0, transitions on the t0 pin will clock the counter even if the pin is configured as an output. this feature allows software control of the counting. timer/counter register ? tcnt0 the timer/counter register gives direct access, both for read and write operations, to the timer/counter unit 8-bit counter. writing to the tcnt0 register blocks (removes) the compare match on the following timer clock. modifying the counter (tcnt0) while the counter is running, introduces a risk of missing a compare match between tcnt0 and the ocr0 register. output compare register ? ocr0 the output compare register contains an 8-bit value that is continuously compared with the counter value (tcnt0). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc0 pin. timer/counter interrupt mask register ? timsk ? bit 1 ? ocie0: timer/counter0 output compare match interrupt enable when the ocie0 bit is written to one, and the i-bit in the status register is set (one), the timer/counter0 compare match interrupt is enabled. the corresponding interrupt is executed if a compare match in timer/counter0 occurs (i.e., when the ocf0 bit is set in the timer/counter interrupt flag register ? tifr). table 43. clock select bit description cs02 cs01 cs00 description 0 0 0 no clock source (timer/counter stopped). 001clk i/o /(no prescaling) 010clk i/o /8 (from prescaler) 011clk i/o /64 (from prescaler) 100clk i/o /256 (from prescaler) 101clk i/o /1024 (from prescaler) 1 1 0 external clock source on t0 pin. clock on falling edge. 1 1 1 external clock source on t0 pin. clock on rising edge. bit 76543210 tcnt0[7:0] tcnt0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ocr0[7:0] ocr0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ocie2 toie2 ticie1 ocie1a ocie1b toie1 ocie0 toie0 timsk read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
86 atmega8535(l) 2502k?avr?10/06 ? bit 0 ? toie0: timer/counter0 overflow interrupt enable when the toie0 bit is written to one, and the i-bit in the status register is set (one), the timer/counter0 overflow interrupt is enable d. the corresponding interrupt is executed if an overflow in timer/counter0 occurs (i.e., when the tov0 bit is set in the timer/counter interrupt flag register ? tifr). timer/counter interrupt flag register ? tifr ? bit 1 ? ocf0: output compare flag 0 the ocf0 bit is set (one) when a compar e match occurs between the timer/counter0 and the data in ocr0 ? output compare register0. ocf0 is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, ocf0 is cleared by writing a logic one to the flag. when the i-bit in sreg, ocie0 (timer/counter0 com- pare match interrupt enable), and ocf0 are set (one), the timer/counter0 compare match interrupt is executed. ? bit 0 ? tov0: timer/counter0 overflow flag the bit tov0 is set (one) when an overflow occurs in timer/counter0. tov0 is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, tov0 is cleared by writing a logic one to the flag. when the sreg i-bit, toie0 (timer/counter0 overflow interrupt enable), and tov0 are set (one), the timer/counter0 overflow interrupt is execut ed. in phase correct pwm mode, this bit is set when timer/counter0 changes counting direction at 0x00. bit 76543210 ocf2 tov2 icf1 ocf1a ocf1b tov1 ocf0 tov0 tifr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
87 atmega8535(l) 2502k?avr?10/06 timer/counter0 and timer/counter1 prescalers timer/counter1 and timer/counter0 share the same prescaler module, but the timer/counters can have different prescaler settings. the description below applies to both timer/counter1 and timer/counter0. internal clock source the timer/counter can be clocked direct ly by the system clock (by setting the csn2:0 = 1). this provides the fastest operat ion, with a maximum timer/counter clock frequency equal to system clock frequency (f clk_i/o ). alternatively, one of four taps from the prescaler can be used as a clock source. the prescaled clock has a frequency of either f clk_i/o /8, f clk_i/o /64, f clk_i/o /256, or f clk_i/o /1024. prescaler reset the prescaler is free running (i.e., operates independently of the clock select logic of the timer/counter) and it is shared by timer/co unter1 and timer/counter0. since the pres- caler is not affected by the timer/counter?s clock select , the state of the prescaler will have implications for situations where a pres caled clock is used. one example of pres- caling artifacts occurs when the timer is enabled and clocked by the prescaler (6 > csn2:0 > 1). the number of system clock cycles from when the timer is enabled to the first count occurs can be from 1 to n+1 system clock cycles, where n equals the prescaler divisor (8, 64, 256, or 1024). it is possible to use the prescaler reset for synchronizing the timer/counter to program execution. however, care must be taken if the other timer/counter that shares the same prescaler also uses prescaling. a pr escaler reset will affect the prescaler period for all timer/counters it is connected to. external clock source an external clock source applied to the t1/t0 pin can be used as timer/counter clock (clk t1 /clk t0 ). the t1/t0 pin is sampled once every system clock cycle by the pin syn- chronization logic. the synchronized (sampled) signal is then passed through the edge detector. figure 38 shows a functional equivalent block diagram of the t1/t0 synchroni- zation and edge detector logic. the registers are clocked at the positive edge of the internal system clock ( clk i/o ). the latch is transparent in the high period of the internal system clock. the edge detector generates one clk t1 /clk t 0 pulse for each positive (csn2:0 = 7) or neg- ative (csn2:0 = 6) edge it detects. figure 38. t1/t0 pin sampling the synchronization and edge detector logic introduces a delay of 2.5 to 3.5 system clock cycles from an edge has been applied to the t1/t0 pin to the counter is updated. enabling and disabling of the clock input must be done when t1/t0 has been stable for at least one system clock cycle, otherwise it is a risk that a false timer/counter clock pulse is generated. tn_sync (to clock select logic) edge detector synchronization dq dq le dq tn clk i/o
88 atmega8535(l) 2502k?avr?10/06 each half period of the exte rnal clock applied must be longer than one system clock cycle to ensure correct sampling. the external clock must be guaranteed to have less than half the system clock frequency (f extclk < f clk_i/o /2) given a 50/50% duty cycle. since the edge detector uses sampling, the maximum frequency of an external clock it can detect is half the sampling frequency (nyquist sampling theorem). however, due to vari- ation of the system clock freq uency and duty cycle caused by oscillator source (crystal, resonator, and capacitors) tolerances, it is recommended that maximum frequency of an external clock source is less than f clk_i/o /2.5. an external clock source can not be prescaled. figure 39. prescaler for timer/counter0 and timer/counter1 (1) note: 1. the synchronization logic on the input pins ( t1/t0) is shown in figure 38. special function io register ? sfior ? bit 0 ? psr10: prescaler reset timer/counter1 and timer/counter0 when this bit is written to one, the timer/co unter1 and timer/co unter0 prescaler will be reset. the bit will be cleared by hardware after the operation is performed. writing a zero to this bit will have no effect. note that timer/counter1 and timer/counter0 share the same prescaler and a reset of this prescaler will af fect both timers. this bit will always be read as zero. psr10 clear clk t1 clk t0 t1 t0 clk i/o synchronization synchronization bit 7 6 5 4 3 2 1 0 adts2 adts1 adts0 ? acme pud psr2 psr10 sfior read/write r/w r/w r/w r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
89 atmega8535(l) 2502k?avr?10/06 16-bit timer/counter1 the 16-bit timer/counter unit allows accura te program execution timing (event man- agement), wave generation, and signal timing measurement. the main features are: ? true 16-bit design (i.e., allows 16-bit pwm) ? two independent output compare units ? double buffered out put compare registers ? one input capture unit ? input capture noise canceler ? clear timer on compar e match (auto reload) ? glitch-free, phase correct pu lse width modulator (pwm) ? variable pwm period ? frequency generator ? external event counter ? four independent interrupt sources (tov1, ocf1a, ocf1b, and icf1) overview most register and bit references in this se ction are written in general form. a lower case ?n? replaces the timer/counter number, and a lower case ?x? replaces the output com- pare unit channel. however, when using the register or bit defines in a program, the precise form must be used, i.e., tcnt1 for accessing timer/counter1 counter value and so on. a simplified block diagram of the 16-bit time r/counter is shown in figure 40. for the actual placement of i/o pins, refer to ?pinout atmega8535? on page 2. cpu accessible i/o registers, including i/o bits and i/o pins , are shown in bold. the device-specific i/o register and bit locations are listed in the ?16-bit timer/counter register description? on page 110.
90 atmega8535(l) 2502k?avr?10/06 figure 40. 16-bit timer/counter block diagram (1) note: 1. refer to figure 1 on page 2, table 26 on page 60, and table 32 on page 64 for timer/counter1 pin placement and description. registers the timer/counter (tcnt1), output compare registers (ocr1a/b), and input capture register (icr1) are all 16-bit registers. special procedures must be followed when accessing the 16-bit registers. these procedur es are described in the section ?access- ing 16-bit registers? on page 92. the timer/counter co ntrol registers (tccr1a/b) are 8-bit registers and have no cpu access restrictions. interrupt requests (abbreviated to int.req. in the figure) signals are all visible in the timer interrupt flag register (tifr). all interrupts are individually masked with the timer interrupt mask register (timsk). tifr and timsk are not shown in the figure since these registers are shared by other timer units. the timer/counter can be clocked internally, via the prescaler, or by an external clock source on the t1 pin. the clock select logic block controls which clock source and edge the timer/counter uses to increment (or decrement) its value. the timer/counter is inactive when no cloc k source is selected. the output from the clock select logic is referred to as the timer clock (clk t 1 ). the double buffered output compare registers (ocr1a/b) are compared with the timer/counter value at all times. the result of the compare can be used by the clock select timer/counter data b u s ocrna ocrnb icrn = = tcntn waveform generation waveform generation ocna ocnb noise canceler icpn = fixed top values edge detector control logic = 0 top bottom count clear direction tovn (int.req.) ocna (int.req.) ocnb (int.req.) icfn (int.req.) tccrna tccrnb ( from analog comparator ouput ) tn edge detector ( from prescaler ) clk tn
91 atmega8535(l) 2502k?avr?10/06 waveform generator to generate a pwm or variable frequency output on the output compare pin (oc1a/b). see ?output compare units? on page 98. the compare match event will also set the compare match flag (o cf1a/b) which can be used to generate an output compare interrupt request. the input capture register can capture the timer/counter value at a given external (edge triggered) event on either the input capture pin (icp1) or on the analog compar- ator pins (see ?analog comparator? on page 203.) the input capture unit includes a digital filtering unit (noise canceler) for reducing the chance of capturing noise spikes. the top value, or maximum timer/counter value, can in some modes of operation be defined by either the ocr1a register, the icr1 register, or by a set of fixed values. when using ocr1a as top value in a pwm mode, the ocr1a register can not be used for generating a pwm out put. however, the top value will, in this case, be double buffered allowing the top value to be changed in run time. if a fixed top value is required, the icr1 register can be used as an alternative, freeing the ocr1a to be used as pwm output. definitions the following definitions are used extensively throughout the document compatibility the 16-bit timer/counter has been updated an d improved from previous versions of the 16-bit avr timer/counter. this 16-bit timer/counter is fully compatible with the earlier version regarding: ? all 16-bit timer/counter related i/o register address locations, including timer interrupt registers. ? bit locations inside all 16-b it timer/counter registers, including timer interrupt registers. ? interrupt vectors. the following control bits have changed names, but have the same functionality and register location: ? pwm10 is changed to wgm10. ? pwm11 is changed to wgm11. ? ctc1 is changed to wgm12. the following bits are added to the 16-bit timer/counter control registers: ? foc1a and foc1b are added to tccr1a. ? wgm13 is added to tccr1b. the 16-bit timer/counter has improvements that will affect the compatibility in some special cases. table 44. definitions bottom the counter reaches the bottom when it becomes 0x0000. max the counter reaches its max imum when it becomes 0xffff (decimal 65535). top the counter reaches the top when it becomes equal to the highest value in the count sequence. the top value can be assigned to be one of the fixed values: 0x00ff, 0x01ff, or 0x03ff, or to the value stored in the ocr1a or icr1 register. the assignment is dependent of the mode of operation.
92 atmega8535(l) 2502k?avr?10/06 accessing 16-bit registers the tcnt1, ocr1a/b, and icr1 are 16-bit registers that can be accessed by the avr cpu via the 8-bit data bus. the 16-bit register must be byte accessed using two read or write operations. each 16-bit timer has a single 8-bit register for temporary storing of the high byte of the 16-bit access. the same temporary register is shared between all 16-bit registers within each 16-bit timer. accessing the low byte triggers the 16-bit read or write operation. when the low byte of a 16-bit register is written by the cpu, the high byte stored in the temporary register, and the low byte written are both copied into the 16-bit register in the same clock cycle. when the low byte of a 16-bit register is read by the cpu, the high byte of the 16-bit register is copied into the temporary register in the same clock cycle as the low byte is read. not all 16-bit accesses uses the temporary register for the high byte. reading the ocr1a/b 16-bit registers does not involve using the temporary register. to do a 16-bit write, the high byte must be written before the low byte . for a 16-bit read, the low byte must be read before the high byte . the following code examples show how to access the 16-bit timer registers assuming that no interrupts update the temporary register. the same principle can be used directly for accessing the ocr1a/b and icr1 registers. note that when using ?c?, the compiler handles the 16-bit access. note: 1. see ?about code examples? on page 7. the assembly code example returns the tcnt1 value in the r17:r16 register pair. it is important to notice that accessing 16-bit registers are atomic operations. if an inter- rupt occurs between the two instructions accessing the 16-bit register, and the interrupt code updates the temporary register by accessing the same or any other of the 16-bit timer registers, then the result of the access outside the interrupt will be corrupted. therefore, when both the main code and the interrupt code update the temporary regis- ter, the main code must disable the interrupts during the 16-bit access. assembly code examples (1) ... ; set tcnt 1 to 0x01ff ldi r17,0x01 ldi r16,0xff out tcnt 1 h,r17 out tcnt 1 l,r16 ; read tcnt 1 into r17:r16 in r16,tcnt 1 l in r17,tcnt 1 h ... c code examples (1) unsigned int i; ... /* set tcnt 1 to 0x01ff */ tcnt 1 = 0x1ff; /* read tcnt 1 into i */ i = tcnt 1 ; ...
93 atmega8535(l) 2502k?avr?10/06 the following code examples show how to do an atomic read of the tcnt1 register contents. reading any of the ocr1a/b or icr1 registers can be done by using the same principle. note: 1. see ?about code examples? on page 7. the assembly code example returns the tcnt1 value in the r17:r16 register pair. assembly code example (1) tim16_readtcnt 1 : ; save global interrupt flag in r18,sreg ; disable interrupts cli ; read tcnt 1 into r17:r16 in r16,tcnt 1 l in r17,tcnt 1 h ; restore global interrupt flag out sreg,r18 ret c code example (1) unsigned int tim16_readtcnt 1 ( void ) { unsigned char sreg; unsigned int i; /* save global interrupt flag */ sreg = sreg; /* disable interrupts */ _cli(); /* read tcnt 1 into i */ i = tcnt 1 ; /* restore global interrupt flag */ sreg = sreg; return i; }
94 atmega8535(l) 2502k?avr?10/06 the following code examples show how to do an atomic write of the tcnt1 register contents. writing any of the ocr1a/b or icr1 registers can be done by using the same principle. note: 1. see ?about code examples? on page 7. the assembly code example requires that the r17:r16 register pair contains the value to be written to tcnt1. re-using the temporary high byte register if writing to more than one 16-bit register where the high byte is the same for all registers written, then the high byte only needs to be written once. however, note that the same rule of atomic operation described pr eviously also applies in this case. assembly code example (1) tim16_writetcnt 1 : ; save global interrupt flag in r18,sreg ; disable interrupts cli ; set tcnt 1 to r17:r16 out tcnt 1 h,r17 out tcnt 1 l,r16 ; restore global interrupt flag out sreg,r18 ret c code example (1) void tim16_writetcnt 1 ( unsigned int i ) { unsigned char sreg; /* save global interrupt flag */ sreg = sreg; /* disable interrupts */ _cli(); /* set tcnt 1 to i */ tcnt 1 = i; /* restore global interrupt flag */ sreg = sreg; }
95 atmega8535(l) 2502k?avr?10/06 timer/counter clock sources the timer/counter can be clocked by an intern al or an external clock source. the clock source is selected by the clock sele ct logic which is controlled by the clock select (cs12:0) bits located in the timer/counter control register b (tccr1b). for details on clock sources and pre scaler, see ?timer/counter0 and timer/counter1 prescalers? on page 87. counter unit the main part of the 16-bit timer/counter is the programmable 16-bit bi-directional counter unit. figure 41 shows a block diagram of the counter and its surroundings. figure 41. counter unit block diagram signal description (internal signals): count increment or decrement tcnt1 by 1. direction select between increment and decrement. clear clear tcnt1 (set all bits to zero). clk t 1 timer/counter clock. top signalize that tcnt1 has reached maximum value. bottom signalize that tcnt1 has reached minimum value (zero). the 16-bit counter is mapped into two 8-bit i/o memory locations: counter high (tcnt1h) containing the upper eight bits of the counter, and counter low (tcnt1l) containing the lower eight bits. the tcnt1h register can only be indirectly accessed by the cpu. when the cpu does an access to the tcnt1h i/o location, the cpu accesses the high byte temporary register (temp). the temporary register is updated with the tcnt1h value when the tcnt1l is read, and tcnt1h is updated with the temporary register value when tcnt1l is writ ten. this allows the cpu to read or write the entire 16-bit counter value within one cl ock cycle via the 8-bit data bus. it is impor- tant to notice that there are special cases of writing to the tcnt1 register when the counter is counting that will give unpredictable results. the special cases are described in the sections where they are of importance. depending on the mode of operation used, the counter is cleared, incremented, or dec- remented at each timer clock (clk t 1 ). the clk t 1 can be generated from an external or internal clock source, selected by the clock select bits (cs12:0). when no clock source is selected (cs12:0 = 0) the timer is stopped. however, the tcnt1 value can be accessed by the cpu, independent of whether clk t 1 is present or not. a cpu write over- rides (has priority over) all counter clear or count operations. the counting sequence is determined by the setting of the waveform generation mode bits (wgm13:0) located in the timer/counter control registers a and b (tccr1a and temp (8-bit) data bus (8-bit) tcntn (16-bit counter) tcntnh (8-bit) tcntnl (8-bit) control logic count clear direction tovn (int.req.) clock select top bottom tn edge detector ( from prescaler ) clk tn
96 atmega8535(l) 2502k?avr?10/06 tccr1b). there are close connections between how the counter behaves (counts) and how waveforms are generated on the output compare outputs oc1x. for more details about advanced counting sequences and waveform generation, see ?modes of opera- tion? on page 101. the timer/counter overflow flag (tov1) is set according to the mode of operation selected by the wgm13:0 bits. tov1 can be used for generating a cpu interrupt. input capture unit the timer/counter incorporates an input capt ure unit that can capture external events and give them a time-stamp indicating time of occurrence. the external signal indicating an event, or multiple events, can be applied via the icp1 pin or alternatively, via the analog comparator unit. the time-stamps can th en be used to calculate frequency, duty- cycle, and other features of the signal a pplied. alternatively the time-stamps can be used for creating a log of the events. the input capture unit is illustrated by the block diagram shown in figure 42. the ele- ments of the block diagram that are not directly a part of the input capture unit are gray shaded. the small ?n? in register and bit names indicates the timer/counter number. figure 42. input capture unit block diagram when a change of the logic level (an event) occurs on the input capture pin (icp1), alternatively on the analog comparator output (aco), and this change confirms to the setting of the edge de tector, a capture will be triggered. when a captur e is triggered, the 16-bit value of the counter (tcnt1) is written to the input capture register (icr1). the input capture flag (icf1) is set at the same system clock as the tcnt1 value is copied into icr1 register. if enabled (ticie1 = 1), the input capture flag generates an input capture interrupt. the icf1 flag is automatic ally cleared when the interrupt is executed. alternatively the icf1 flag can be cleared by software by writing a logical one to its i/o bit location. reading the 16-bit value in the input capture register (icr1) is done by first reading the low byte (icr1l) and then the high byte (icr1h). when the low byte is read the high icfn (int.req.) analog comparator write icrn (16-bit register) icrnh (8-bit) noise canceler icpn edge detector temp (8-bit) data bus (8-bit) icrnl (8-bit) tcntn (16-bit counter) tcntnh (8-bit) tcntnl (8-bit) acic* icnc ices aco*
97 atmega8535(l) 2502k?avr?10/06 byte is copied into the high byte tempor ary register (temp). when the cpu reads the icr1h i/o location it will a ccess the temp register. the icr1 register can only be written when using a waveform generation mode that utilizes the icr1 register for defining the counter?s top value. in these cases the waveform generation mode (wgm13:0) bits must be set before the top value can be written to the icr1 register. when writing the icr1 register the high byte must be writ- ten to the icr1h i/o location before the low byte is written to icr1l. for more information on how to access the 16-bit registers, refer to ?accessing 16-bit registers? on page 92. input capture trigger source the main trigger source for the input capture unit is the input capture pin (icp1). timer/counter1 can alternatively use the a nalog comparator output as trigger source for the input capture unit. the analog comparat or is selected as trigger source by set- ting the analog comparator input capture (acic) bit in the analog comparator control and status register (acsr). be aware that changing trigger source can trigger a cap- ture. the input capture flag must therefore be cleared after the change. both the input capture pin (icp1) and the analog comparator output (aco) inputs are sampled using the same technique as t he t1 pin (figure 38 on page 87). the edge detector is also identical. ho wever, when the noise canceler is enabled, additional logic is inserted before the edge detector, which increases the delay by four system clock cycles. note that the input of the noise canceler and edge detector is always enabled unless the timer/counter is set in a waveform generation mode that uses icr1 to define top. an input capture can be triggered by software by contro lling the port of the icp1 pin. noise canceler the noise canceler improves noise immunity by using a simple digital filtering scheme. the noise canceler input is monitored over four samples, and all four must be equal for changing the output that, in turn, is used by the edge detector. the noise canceler is enabled by setting the input capture noise canceler (icnc1) bit in timer/counter control register b (tccr1b). when enabled, the noise canceler introduces additional four system clock cycles of delay from a change applied to the input, to the update of the icr1 register. the noise canceler uses the system clock and is therefore not affected by the prescaler. using the input capture unit the main challenge when using the input capture unit is to assign enough processor capacity for handling the incoming events. the time between two events is critical. if the processor has not read the captured value in the icr1 register before the next event occurs, the icr1 will be overwritten with a new va lue. in this case the result of the cap- ture will be incorrect. when using the input capture interrupt, the icr1 register should be read as early in the interrupt handler routine as possible. even though the input capture interrupt has rela- tively high priority, the maximum interrupt response time is dependent on the maximum number of clock cycles it takes to handle any of the other interrupt requests. using the input capture unit in any mode of operation when the top value (resolution) is actively changed during operation, is not recommended. measurement of an external signal?s duty cycle requires that the trigger edge is changed after each capture. changing the edge sensing must be done as early as possible after the icr1 register has been read. after a change of the edge, the input capture flag (icf1) must be cleared by software (writing a logical one to the i/o bit location). for
98 atmega8535(l) 2502k?avr?10/06 measuring frequency only, the clearing of the icf1 flag is not required (if an interrupt handler is used). output compare units the 16-bit comparator continuously compares tcnt1 with the output compare regis- ter (ocr1x). if tcnt equals ocr1x the comparator signals a match. a match will set the output compare flag (ocf1x) at the next timer cl ock cycle. if enabled (ocie1x = 1), the output compare flag generates an output compare interrupt. the ocf1x flag is automatically cleared when the interrupt is executed. alternatively the ocf1x flag can be cleared by software by writing a logical one to its i/o bit location. the waveform gen- erator uses the match signal to generate an output according to operating mode set by the waveform generation mode (wgm13:0) bits and compare output mode (com1x1:0) bits. the top and bottom signals are used by the waveform generator for handling the special cases of the extreme values in some modes of operation. (see ?modes of operation? on page 101.) a special feature of output compare unit a allows it to define the timer/counter top value (i.e., counter resolution). in addition to the counter resolution, the top value defines the period time for waveforms generated by the waveform generator. figure 43 shows a block diagram of the output compare unit. the small ?n? in the regis- ter and bit names indicates the device number (n = 1 for timer/counter1), and the ?x? indicates output compare unit (a/b). the elements of the block diagram that are not directly a part of the output compare unit are gray shaded. figure 43. output compare unit, block diagram the ocr1x register is double buffered when using any of the twelve pulse width mod- ulation (pwm) modes. for the normal and clear timer on compare (ctc) modes of operation, the double buffering is disabled. the double buffering synchronizes the update of the ocr1x compare register to either top or bottom of the counting ocfnx (int.req.) = (16-bit comparator ) ocrnx buffer (16-bit register) ocrnxh buf. (8-bit) ocnx temp (8-bit) data bus (8-bit) ocrnxl buf. (8-bit) tcntn (16-bit counter) tcntnh (8-bit) tcntnl (8-bit) comnx1:0 wgmn3:0 ocrnx (16-bit register) ocrnxh (8-bit) ocrnxl (8-bit) waveform generator top bottom
99 atmega8535(l) 2502k?avr?10/06 sequence. the synchronization prevents the occurrence of odd-length, non-symmetrical pwm pulses, thereby making the output glitch-free. the ocr1x register access may seem complex, but this is not the case. when the double buffering is enabled, the cpu has access to the ocr1x buffer register, and if double buffering is disabled the cpu will access the ocr1x di rectly. the content of the ocr1x (buffer or compare) register is only changed by a write operation (the timer/counter does not update this register automatically as does the tcnt1? and icr1 register). therefore ocr1x is not read via the high byte temporary register (temp). however, it is a good practice to read the low byte first as with accessing other 16-bit registers. writing the ocr1x registers must be done via the temp register since the compare of all 16 bits is done co ntinuously. the high byte (ocr1xh) has to be written first. when the high byte i/o location is written by the cpu, the temp register will be updated by the value writ ten. then when the low byte (ocr1xl) is written to the lower eight bits, the high byte will be copied into the upper 8-bits of either the ocr1x buffer or ocr1x co mpare register in the same system clock cycle. for more information of how to access the 16-bit registers refer to ?accessing 16-bit registers? on page 92. force output compare in non-pwm waveform generation modes, the match output of the comparator can be forced by writing a one to the force output compare (foc1x) bit. forcing compare match will not set the ocf1x flag or reload /clear the timer, but the oc1x pin will be updated as if a real compare match had occurred (the com11:0 bits settings define whether the oc1x pin is set, cleared or toggled). compare match blocking by tcnt1 write all cpu writes to the tcnt1 register will block any compare match that occurs in the next timer clock cycle, even when the timer is stopped. this feature allows ocr1x to be initialized to the same value as tcnt1 without triggering an interrupt when the timer/counter clock is enabled. using the output compare unit since writing tcnt1 in any mode of operat ion will block all compare matches for one timer clock cycle, there are risks involved when changing tcnt1 when using any of the output compare channels, independent of whether the timer/counter is running or not. if the value written to tcnt1 equals the ocr1x value, the compare match will be missed, resulting in incorrect waveform generation. do not write the tcnt1 equal to top in pwm modes with variable top valu es. the compare match for the top will be ignored and the counter will cont inue to 0xffff. sim ilarly, do not writ e the tcnt1 value equal to bottom when the counter is down-counting. the setup of the oc1x should be performed before setting the data direction register for the port pin to output. the easiest way of setting the oc1x value is to use the force output compare (foc1x) strobe bits in normal mode. the oc1x register keeps its value even when changing between waveform generation modes. be aware that the com1x1:0 bits are not double buffered together with the compare value. changing the com1x1:0 bi ts will take effect immediately.
100 atmega8535(l) 2502k?avr?10/06 compare match output unit the compare output mode (com1x1:0) bits have two functions. the waveform genera- tor uses the com1x1:0 bits for defining the output compare (oc1x) state at the next compare match. secondly the com1x1:0 bits control the oc1x pin output source. fig- ure 44 shows a simplified schematic of the logic affected by the com1x1:0 bit setting. the i/o registers, i/o bits, and i/o pins in the figure are shown in bold. only the parts of the general i/o port contro l registers (ddr and port) that are affected by the com1x1:0 bits are shown. when referring to the oc1x state, the reference is for the internal oc1x register, not the oc1x pin. if a system reset occurs, the oc1x register is reset to ?0?. figure 44. compare match output unit, schematic the general i/o port function is overridden by the output compare (oc1x) from the waveform generator if either of the com1x1:0 bits are set. however, the oc1x pin direction (input or output ) is still controlled by the data direction register (ddr) for the port pin. the data direction register bit for the oc1x pin (ddr_oc1x) must be set as output before the oc1x value is visible on th e pin. the port override function is generally independent of the waveform generation mode, but there are some exceptions. refer to table 45, table 46 and table 47 for details. the design of the output compare pin logic allows initialization of the oc1x state before the output is enabled. note that some com1x1:0 bit settings are reserved for certain modes of operation. see ?16-bit timer/counter register description? on page 110. the com1x1:0 bits have no effect on the input capture unit. compare output mode and waveform generation the waveform generator uses the com1x1:0 bits differently in normal, ctc, and pwm modes. for all modes, setting the com1x1:0 = 0 tells the waveform generator that no action on the oc1x register is to be performed on the next compare match. for com- pare output actions in the non-pwm modes refer to table 45 on page 110. for fast pwm mode refer to table 46 on page 111, and for phase correct and phase and fre- quency correct pwm refer to table 47 on page 111. port ddr dq dq ocnx pin ocnx dq waveform generator comnx1 comnx0 0 1 data b u s focnx clk i/o
101 atmega8535(l) 2502k?avr?10/06 a change of the com1x1:0 bits state will have effect at the first compare match after the bits are written. for non-pwm modes, the action can be forced to have immediate effect by using the foc1x strobe bits. modes of operation the mode of operation, i.e., the behavior of the timer/counter and the output compare pins, is defined by the combination of the waveform generation mode (wgm13:0) and compare output mode (com1x1:0) bits. the compare output mode bits do not affect the counting sequence, while the waveform generation mode bits do. the com1x1:0 bits control whether the pwm output generated should be inverted or not (inverted or non-inverted pwm). for non-pwm modes the com1x1:0 bits control whether the out- put should be set, cleared or toggle at a compare match (see ?compare match output unit? on page 100.) for detailed timing information refer to ?timer/counter timing diagrams? on page 108. normal mode the simplest mode of operation is the normal mode (wgm13:0 = 0). in this mode the counting direction is always up (incrementing), and no counter clear is performed. the counter simply overruns when it passes its maximum 16-bit value (max = 0xffff) and then restarts from the bottom (0x0000). in normal operation the timer/counter over- flow flag (tov1) will be set in the same time r clock cycle as the tcnt1 becomes zero. the tov1 flag in this case behaves like a 17th bit, except that it is only set, not cleared. however, combined with the timer overflow interrupt that automatically clears the tov1 flag, the timer resolution can be increased by software. there are no special cases to consider in the normal mode, a new counter value can be written anytime. the input capture unit is easy to use in normal mode. however, observe that the maxi- mum interval between the external events must not exceed the resolution of the counter. if the interval between events are too long, the timer overflow interrupt or the prescaler must be used to extend the resolution for the capture unit. the output compare units can be used to generate interrupts at some given time. using the output compare to generate waveforms in normal mode is not recommended, since this will occupy too much of the cpu time. clear timer on compare match (ctc) mode in clear timer on compare or ctc mode (wgm13:0 = 4 or 12), the ocr1a or icr1 register is used to manipulate the counter resolution. in ctc mode the counter is cleared to zero when the counter value (tcnt1) matches either the ocr1a (wgm13:0 = 4) or the icr1 (wgm13:0 = 12). the ocr1a or icr1 define the top value for the counter, hence also its resolution. this mode allows greater control of the compare match output frequency. it also simplifies th e operation of counting external events. the timing diagram for the ctc mode is shown in figure 45. the counter value (tcnt1) increases until a compare match occurs with either ocr1a or icr1, and then counter (tcnt1) is cleared.
102 atmega8535(l) 2502k?avr?10/06 figure 45. ctc mode, timing diagram an interrupt can be generated each time the counter value reaches the top value by either using the ocf1a or icf1 flag according to the register used to define the top value. if the interrupt is enabled, the interrupt handler routine can be used for updating the top value. however, changing the top to a value close to bottom when the counter is running with a low or no prescaler value must be done with care since the ctc mode does not have the double buffering feature. if the new value written to ocr1a or icr1 is lower than the current value of tcnt1, the counter will miss the compare match. the counter will then have to count to its maximum value (0xffff) and wrap around starting at 0x0000 before the compare match can occur. in many cases this feature is not desi rable. an alternative will then be to use the fast pwm mode using ocr1a for defining top (wgm13:0 = 15) since the ocr1a then will be double buffered. for generating a waveform output in ctc mode, the oc1a output can be set to toggle its logical level on each compare match by setting the compare output mode bits to tog- gle mode (com1a1:0 = 1). the oc1a value w ill not be visible on the port pin unless the data direction for the pin is set to output (ddr_oc1a = 1). the waveform generated will have a maximum frequency of f oc 1 a = f clk_i/o /2 when ocr1a is set to zero (0x0000). the waveform frequency is defined by the following equation: the n variable represents the prescaler factor (1, 8, 64, 256, or 1024). as for the normal mode of operation, the tov1 flag is set in the same timer clock cycle that the counter counts from max to 0x0000. fast pwm mode the fast pulse width modulation or fast pwm mode (wgm13:0 = 5, 6, 7, 14, or 15) pro- vides a high frequency pwm waveform generation option. the fast pwm differs from the other pwm options by its single-slope operation. the counter counts from bottom to top then restarts from bottom. in non-inverting compare output mode, the output compare (oc1x) is set on the compare match between tcnt1 and ocr1x, and cleared at bottom. in inverting compare output mode output is cleared on compare match and set at bottom. due to the single-slope operation, the operating frequency of the fast pwm mode can be twice as hi gh as the phase correct and phase and fre- quency correct pwm modes that use dual-s lope operation. this high frequency makes the fast pwm mode well suited for power regulation, rectification, and dac applications. tcntn ocna (toggle) ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 4 period 2 3 (comna1:0 = 1) f ocna f clk_i/o 2 n 1 ocrna + () ?? -------------------------------------------------- - =
103 atmega8535(l) 2502k?avr?10/06 high frequency allows physica lly small sized external components (coils, capacitors), hence reducing total system cost. the pwm resolution for fast pwm can be fixed to 8-, 9-, or 10-bit, or defined by either icr1 or ocr1a. the minimum resolution allowed is 2-bit (icr1 or ocr1a set to 0x0003), and the maximum resolution is 16-bit (icr1 or ocr1a set to max). the pwm resolution can be calculated in bits by using the following equation: in fast pwm mode the counter is incremented until the counter value matches either one of the fixed values 0x00ff, 0x01ff, or 0x03ff (wgm13:0 = 5, 6, or 7), the value in icr1 (wgm13:0 = 14), or th e value in ocr1a (wgm13:0 = 15). the counter is then cleared at the following timer clock cycle. the timing diagram for the fast pwm mode is shown in figure 46. the figure shows fast pwm mode when ocr1a or icr1 is used to define top. the tcnt1 value is in the ti ming diagram shown as a histogram for illus- trating the single-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt1 slopes represent compare matches between ocr1x and tcnt1. the oc 1x interrupt flag will be set when a com- pare match occurs. figure 46. fast pwm mode, timing diagram the timer/counter overflow flag (tov1) is set each time the counter reaches top. in addition the oc1a or icf1 flag is set at t he same timer clock cy cle as tov1 is set when either ocr1a or icr1 is used for defining the top value. if one of the interrupts are enabled, the interrupt handler routine can be used for updating the top and com- pare values. when changing the top value the program must ensure that the new top value is higher or equal to the value of all of the co mpare registers. if the top value is lower than any of the compare registers, a compare match will never occur between the tcnt1 and the ocr1x. note that when using fixed top values the unused bits are masked to zero when any of the ocr1x registers are written. the procedure for updating icr1 differs from updating ocr1a when used for defining the top value. the icr1 register is not dou ble buffered. this means that if icr1 is changed to a low value when the counter is running with a low or none prescaler value, there is a risk that the new icr1 value written is lower than the current value of tcnt1. the result will then be that the counter will miss the compare match at the top value. r fpwm top 1 + () log 2 () log ---------------------------------- - = tcntn ocrnx / top update and tovn interrupt flag set and ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 7 period 2 3 4 5 6 8 ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3)
104 atmega8535(l) 2502k?avr?10/06 the counter will then have to count to t he max value (0xffff) and wrap around start- ing at 0x0000 before the compare match can occur. the ocr1a register however, is double buffered. this feature allows the ocr1a i/o location to be written anytime. when the ocr1a i/o location is written the value written will be put into the ocr1a buffer register. the ocr1a compare register will then be updated with the value in the buffer register at the next timer clo ck cycle the tcnt1 matches top. the update is done at the same timer clock cycle as the tcnt1 is cleared and the tov1 flag is set. using the icr1 register for defining top works well when using fixed top values. by using icr1, the ocr1a register is free to be used for generating a pwm output on oc1a. however, if the base pwm frequency is actively changed (by changing the top value), using the ocr1a as top is clearly a better choice due to its double buffer feature. in fast pwm mode, the compare units allow generation of pwm waveforms on the oc1x pins. setting the com1x1:0 bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the com1x1:0 to three (see table 46 on page 111). the actual oc1x value will only be visible on the port pin if the data direc- tion for the port pin is set as output (ddr_oc1x). the pwm waveform is generated by setting (or clearing) the oc1x register at the compare match between ocr1x and tcnt1, and clearing (or setting) the oc1x register at the timer clock cycle the counter is cleared (changes from top to bottom). the pwm frequency for the output can be calculated by the following equation: the ? n ? variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the ocr1x register represents special cases when generating a pwm waveform output in the fast pwm mode. if the ocr1x is set equal to bottom (0x0000) the output will be a na rrow spike for each top+1 timer clock cycle. setting the ocr1x equal to top will result in a constant high or low output (depending on the polar- ity of the output set by the com1x1:0 bits). a frequency (with 50% duty cycle) waveform output in fast pwm mode can be achieved by setting oc1a to toggle its logical le vel on each compare match (com1a1:0 = 1). this applies only if ocr1a is used to define the top value (wgm13:0 = 15). the wave- form generated will have a maximum frequency of f oc 1 a = f clk_i/o /2 when ocr1a is set to zero (0x0000). this feature is similar to the oc1a toggle in ctc mode, except the dou- ble buffer feature of the output compare unit is enabled in the fast pwm mode. phase correct pwm mode the phase correct pulse width modulation or phase correct pwm mode (wgm13:0 = 1, 2, 3, 10, or 11) provides a high resolution phase correct pwm waveform generation option. the phase correct pwm mode is, like the phase and frequency cor- rect pwm mode, based on a dual-slope operation. the counter counts repeatedly from bottom (0x0000) to top and then from top to bottom. in non-inverting compare output mode, the output compare (oc1x) is cleared on the compare match between tcnt1 and ocr1x while up-counting and set on the compare match while down- counting. in inverting output compare mode, the operation is inverted. the dual-slope operation has lower maximum operation frequency than single slope operation. how- ever, due to the symmetric feature of th e dual-slope pwm modes, these modes are preferred for motor control applications. the pwm resolution for the phase correct pwm mode can be fixed to 8-, 9-, or 10-bit, or defined by either icr1 or ocr1a. the minimum resolution allowed is 2-bit (icr1 or f ocnxpwm f clk_i/o n 1 top + () ? ---------------------------------- - =
105 atmega8535(l) 2502k?avr?10/06 ocr1a set to 0x0003), and the maximum resolution is 16-bit (icr1 or ocr1a set to max). the pwm resolution can be calculated in bits by using the following equation: in phase correct pwm mode, the counter is incremented until the counter value matches either one of the fixed values 0x00 ff, 0x01ff, or 0x03ff (wgm13:0 = 1, 2, or 3), the value in icr1 (wgm13:0 = 10), or the value in ocr1a (wgm13:0 = 11). the counter has then reached the top and changes the count direction. the tcnt1 value will be equal to top for one timer clock cycle. the timing diagram for the phase correct pwm mode is shown on figure 47. the figure shows phase correct pwm mode when ocr1a or icr1 is used to define top. the tcnt1 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt1 slopes represent compare matches between ocr1x and tcnt1. the oc1x interrupt flag will be set when a compare match occurs. figure 47. phase correct pwm mode, timing diagram the timer/counter overflow flag (tov1) is set each time the counter reaches bot- tom. when either ocr1a or icr1 is used for defining the top value, the oc1a or icf1 flag is set accordingly at the same timer clock cycle as the ocr1x registers are updated with the double buffer value (at top). the interrupt flags can be used to gener- ate an interrupt each time the counter reaches the top or bottom value. when changing the top value, the program must ensure that the new top value is higher or equal to the value of all of the co mpare registers. if the top value is lower than any of the compare registers, a compare match will never occur between the tcnt1 and the ocr1x. note that when using fixed top values, the unused bits are masked to zero when any of the ocr1x registers are written. as the third period shown in figure 47 illustrates, changing the top ac tively while the timer/ counter is running in the phase correct mode can result in an unsymmetrical output. the reason for this can be found in the time of update of the ocr1x register. since the ocr1x update occurs at top, the pwm period starts and ends at top. this implies that the length of the fall- r pcpwm top 1 + () log 2 () log ---------------------------------- - = ocrnx/top update and ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 2 3 4 tovn interrupt flag set (interrupt on bottom) tcntn period ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3)
106 atmega8535(l) 2502k?avr?10/06 ing slope is determined by the previous top value, while the length of the rising slope is determined by the new top value. when these two values differ the two slopes of the period will differ in length. the difference in length gives the unsymme trical result on the output. it is recommended to use the phase and frequency correct mode instead of the phase correct mode when changing the top value wh ile the timer/counter is running. when using a static top value, there are practica lly no differences between the two modes of operation. in phase correct pwm mode, the compare units allow generation of pwm waveforms on the oc1x pins. setting the com1x1:0 bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the com1x1:0 to three (see table 47 on page 111). the actual oc1x value will only be visible on the port pin if the data direction for the port pin is set as out put (ddr_oc1x). the pwm waveform is gener- ated by setting (or clearing) the oc1x register at the compare match between ocr1x and tcnt1 when the counter increments, and clearing (or setting) the oc1x register at compare match between ocr1x and tcnt1 when the counter decrements. the pwm frequency for the output when using phase correct pwm can be calculated by the fol- lowing equation: the ? n ? variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the ocr1x register represent special cases when generating a pwm waveform output in the phase correct pwm mode. if the ocr1x is set equal to bottom the output will be continuously low and if set equal to top the output will be continuously high for non-inverted pwm mode. for inverted pw m the output will have the opposite logic values. if ocr1a is us ed to define the top value (wgm13:0 = 11) and com1a1:0 = 1, the oc1a output will toggle with a 50% duty cycle. phase and frequency correct pwm mode the phase and frequency correct pulse width modulation, or phase and frequency cor- rect pwm mode (wgm13:0 = 8 or 9) provides a high resolution phase and frequency correct pwm waveform generation option. the phase and frequency correct pwm mode is, like the phase correct pwm mode, based on a dual-slope operation. the counter counts repeatedly from bottom (0x0000) to top and then from top to bot- tom. in non-inverting compare output mode, the output compare (oc1x) is cleared on the compare match between tcnt1 and ocr1x while up-counting, and set on the compare match while down-counting. in inverting compare output mode, the operation is inverted. the dual-slope operation gives a lower maximum operation frequency com- pared to the single-slope operation. however, due to the symmetric feature of the dual- slope pwm modes, these modes are preferred for motor control applications. the main difference between the phase correct and the phase and frequency correct pwm mode is the time the ocr1x register is updated by the ocr1x buffer register, (see figure 47 and figure 48). the pwm resolution for the phase and frequency correct pwm mode can be defined by either icr1 or ocr1a. the minimum resolution allowed is 2-bit (icr1 or ocr1a set to 0x0003), and the maximum resolution is 16-bit (icr1 or ocr1a set to max). the pwm resolution in bits can be calculated using the following equation: f ocnxpcpwm f clk_i/o 2 ntop ?? --------------------------- - = r pfcpwm top 1 + () log 2 () log ---------------------------------- - =
107 atmega8535(l) 2502k?avr?10/06 in phase and frequency correct pwm mode the counter is incremented until the counter value matches either the value in icr1 (wgm13:0 = 8), or the value in ocr1a (wgm13:0 = 9). the counter has then reached the top and changes the count direc- tion. the tcnt1 value will be equal to top for one ti mer clock cycle. the timing diagram for the phase correct and frequency correct pwm mode is shown in figure 48. the figure shows phase and frequency correct pwm mode when ocr1a or icr1 is used to define top. the tcnt1 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt1 slopes represent compare matches between ocr1x and tcnt1. the oc 1x interrupt flag will be set when a com- pare match occurs. figure 48. phase and frequency correct pwm mode, timing diagram the timer/counter overflow flag (tov1) is set at the same timer clock cycle as the ocr1x registers are updated with the double buffer value (at bottom). when either ocr1a or icr1 is used for defining the to p value, the oc1a or icf1 flag set when tcnt1 has reached top. the interrupt flags can then be used to generate an interrupt each time the counter reaches the top or bottom value. when changing the top value the program must ensure that the new top value is higher or equal to the value of all of the co mpare registers. if the top value is lower than any of the compare registers, a compare match will never occur between the tcnt1 and the ocr1x. as figure 48 shows the output generated is, in contrast to the phase correct mode, sym- metrical in all periods. since the ocr1x registers are updated at bottom, the length of the rising and the falling slopes will always be equal. this gives symmetrical output pulses and the frequency is, therefore, correct. using the icr1 register for defining top works well when using fixed top values. by using icr1, the ocr1a register is free to be used for generating a pwm output on oc1a. however, if the base pwm frequency is actively changed by changing the top value, using the ocr1a as top is clearl y a better choice due to its double buffer feature. ocrnx/top update and tovn interrupt flag set (interrupt on bottom) ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 2 3 4 tcntn period ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3)
108 atmega8535(l) 2502k?avr?10/06 in phase and frequency correct pwm mode, the compare units allow generation of pwm waveforms on the oc1x pins. setting the com1x1:0 bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the com1x1:0 to three (see tabl e 47 on page 111). the actual oc1x value will only be vis- ible on the port pin if the data direction for the port pin is set as output (ddr_oc1x). the pwm waveform is generated by setting (or cl earing) the oc1x register at the compare match between ocr1x and tcnt1 when the counter increments, and clearing (or set- ting) the oc1x register at compare match between ocr1x and tcnt1 when the counter decrements. the pwm frequency for the output when using phase and fre- quency correct pwm can be calculated by the following equation: the ? n ? variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the ocr1x register represents special cases when generating a pwm waveform output in the phase correct pwm mode. if the ocr1x is set equal to bottom the output will be continuously low and if set equal to to p, the output will be set to high for non-inverted pwm mode. for inverted pwm, the output will have the opposite logic values. if ocr1a is used to define the top value (wgm13:0 = 9) and com1a1:0 = 1, the oc1a output will toggle with a 50% duty cycle. timer/counter timing diagrams the timer/counter is a synchronous design and the timer clock (clk t1 ) is therefore shown as a clock enable signal in the followi ng figures. the figures include information on when interrupt flags are set, and when the ocr1x register is updated with the ocr1x buffer value (only for mo des utilizing double buffering ). figure 49 shows a timing diagram for the setting of ocf1x. figure 49. timer/counter timing diagram, setting of ocf1x, no prescaling figure 50 shows the same timing data, but with the prescaler enabled. f ocnxpfcpwm f clk_i/o 2 ntop ?? --------------------------- - = clk tn (clk i/o /1) ocfnx clk i/o ocrnx tcntn ocrnx value ocrnx - 1 ocrnx ocrnx + 1 ocrnx + 2
109 atmega8535(l) 2502k?avr?10/06 figure 50. timer/counter timing diagram, setting of ocf1x, with prescaler (f clk_i/o /8) figure 51 shows the count sequence close to top in various modes. when using phase and frequency correct pwm mode, the ocr1x register is updated at bottom. the timing diagrams will be th e same, but top should be replaced by bottom, top-1 by bottom+1 and so on. the same renaming applies for modes that set the tov1 flag at bottom. figure 51. timer/counter timing diagram, no prescaling figure 52 shows the same timing data, but with the prescaler enabled. ocfnx ocrnx tcntn ocrnx value ocrnx - 1 ocrnx ocrnx + 1 ocrnx + 2 clk i/o clk tn (clk i/o /8) tovn (fpwm) and icfn (if used as top) ocrnx (update at top) tcntn (ctc and fpwm) tcntn (pc and pfc pwm) top - 1 top top - 1 top - 2 old ocrnx value new ocrnx value top - 1 top bottom bottom + 1 clk tn (clk i/o /1) clk i/o
110 atmega8535(l) 2502k?avr?10/06 figure 52. timer/counter timing diagram, with prescaler (f clk_i/o /8) 16-bit timer/counter register description timer/counter1 control register a ? tccr1a ? bit 7:6 ? com1a1:0: compare output mode for channel a ? bit 5:4 ? com1b1:0: compare output mode for channel b the com1a1:0 and com1b1:0 control the output compare pins (oc1a and oc1b respectively) behavior. if one or both of t he com1a1:0 bits are written to one, the oc1a output overrides the normal port functionality of the i/o pin it is connected to. if one or both of the com1b1:0 bit are written to one, the oc1b output overrides the normal port functionality of the i/o pin it is connected to. however, note that the data direction reg- ister (ddr) bit corresponding to the oc1a or oc1b pin must be set in order to enable the output driver. when the oc1a or oc1b is connected to the pin, the function of the com1x1:0 bits is dependent of the wgm13:0 bits setting. table 45 shows the com1x1:0 bit functionality when the wgm13:0 bits are set to a normal or a ctc mode (non-pwm). tovn (fpwm) and icfn (if used as top) ocrnx (update at top) tcntn (ctc and fpwm) tcntn (pc and pfc pwm) top - 1 top top - 1 top - 2 old ocrnx value new ocrnx value top - 1 top bottom bottom + 1 clk i/o clk tn (clk i/o /8) bit 7 6 5 4 3210 com1a1 com1a0 com1b1 com1b0 foc1a foc1b wgm11 wgm10 tccr1a read/write r/w r/w r/w r/w w w r/w r/w initial value0 0 0 0 0000 table 45. compare output mode, non-pwm com1a1/ com1b1 com1a0/ com1b0 description 0 0 normal port operation, oc1a/oc1b disconnected. 0 1 toggle oc1a/oc1b on compare match. 1 0 clear oc1a/oc1b on compare match (set output to low level). 1 1 set oc1a/oc1b on compare match (set output to high level).
111 atmega8535(l) 2502k?avr?10/06 table 46 shows the com1x1:0 bit functionalit y when the wgm13:0 bits are set to the fast pwm mode. note: 1. a special case occurs when ocr1a/ocr1b equals top and com1a1/com1b1 is set. in this case the compare match is ignored, but the set or clear is done at top. see ?fast pwm mode? on page 102 for more details. table 47 shows the com1x1:0 bit functionali ty when the wgm13:0 bits are set to the phase correct or the phase and frequency correct, pwm mode. note: 1. a special case occurs when ocr1a/ocr1b equals top and com1a1/com1b1 is set. see ?phase correct pwm mode? on page 104. for more details. ? bit 3 ? foc1a: force output compare for channel a ? bit 2 ? foc1b: force output compare for channel b the foc1a/foc1b bits are only active when the wgm13:0 bits specify a non-pwm mode. however, for ensu ring compatibility with future devices, these bits must be set to zero when tccr1a is written when operating in a pwm mo de. when writing a logical one to the foc1a/foc1b bit, an immediate compare match is forced on the waveform generation unit. the oc1a/oc1b output is changed according to its com1x1:0 bits set- ting. note that the foc1a/foc1b bits are implemented as strobes. therefore it is the value present in the com1x1:0 bits that determine the effect of the forced compare. a foc1a/foc1b strobe will not ge nerate any interrup t nor will it clear the timer in clear timer on compare match (ctc) mode using ocr1a as top. the foc1a/foc1b bits are always read as zero. ? bit 1:0 ? wgm11:0: waveform generation mode table 46. compare output mode, fast pwm (1) com1a1/ com1b1 com1a0/ com1b0 description 0 0 normal port operation, oc1a/oc1b disconnected. 0 1 wgm13:0 = 15: toggle oc1a on compare match, oc1b disconnected (normal port operation). for all other wgm1 settings, normal port operation oc1a/oc1b disconnected. 1 0 clear oc1a/oc1b on compare match, set oc1a/oc1b at top (non-inverting) 1 1 set oc1a/oc1b on compare match, clear oc1a/oc1b at top (inverting) table 47. compare output mode, phase correct and phase and frequency correct pwm (1) com1a1/ com1b1 com1a0/ com1b0 description 0 0 normal port operation, oc1a/oc1b disconnected. 0 1 wgm13:0 = 9 or 14: toggle oc1a on compare match, oc1b disconnected (normal port operation) . for all other wgm1 settings, normal port operation, oc1a/oc1b disconnected. 1 0 clear oc1a/oc1b on compare match when up-counting. set oc1a/oc1b on compare match when down-counting. 1 1 set oc1a/oc1b on compare match when up-counting. clear oc1a/oc1b on compare match when down-counting.
112 atmega8535(l) 2502k?avr?10/06 combined with the wgm13:2 bits found in the tccr1b register, these bits control the counting sequence of the counter, the source for maximum (top) counter value, and what type of waveform generation to be used, see table 48. modes of operation supported by the timer/counter unit are: normal mode (counter), clear timer on compare match (ctc) mode, and three types of pulse width modulation (pwm) modes. see ?modes of operation? on page 101. note: 1. the ctc1 and pwm11:0 bit definition names are obsolete . use the wgm12:0 definitions. however, the functionality and location of these bits are compatible with previous versions of the timer. table 48. waveform generation mode bit description (1) mode wgm13 wgm12 (ctc1) wgm11 (pwm11) wgm10 (pwm10) timer/counter mode of operation top update of ocr1 x at tov1 flag set on 0 0 0 0 0 normal 0xffff immediate max 1 0 0 0 1 pwm, phase correct, 8-bit 0x00ff top bottom 2 0 0 1 0 pwm, phase correct, 9-bit 0x01ff top bottom 3 0 0 1 1 pwm, phase correct, 10-bit 0x03ff top bottom 4 0 1 0 0 ctc ocr1a immediate max 5 0 1 0 1 fast pwm, 8-bit 0x00ff bottom top 6 0 1 1 0 fast pwm, 9-bit 0x01ff bottom top 7 0 1 1 1 fast pwm, 10-bit 0x03ff bottom top 8 1 0 0 0 pwm, phase and frequency correct icr1 bottom bottom 9 1 0 0 1 pwm, phase and frequency correct ocr1a bottom bottom 10 1 0 1 0 pwm, phase correct icr1 top bottom 11 1 0 1 1 pwm, phase correct ocr1a top bottom 12 1 1 0 0 ctc icr1 immediate max 13 1 1 0 1 reserved ? ? ? 14 1 1 1 0 fast pwm icr1 bottom top 15 1 1 1 1 fast pwm ocr1a bottom top
113 atmega8535(l) 2502k?avr?10/06 timer/counter1 control register b ? tccr1b ? bit 7 ? icnc1: input capture noise canceler setting this bit (to one) activates the input capture noise canceler. when the noise canceler is activated, the input from the i nput capture pin (icp1) is filtered. the filter function requires four successive equal valued samples of the icp1 pin for changing its output. the input capture is therefore delayed by four oscillator cycles when the noise canceler is enabled. ? bit 6 ? ices1: input capture edge select this bit selects which edge on the input capture pin (icp1) is used to trigger a capture event. when the ices1 bit is written to zero , a falling (negative) ed ge is used as trigger, and when the ices1 bit is written to one, a rising (positive) edge will trigger the capture. when a capture is triggered according to t he ices1 setting, the counter value is copied into the input capture register (icr1). t he event will also set the input capture flag (icf1), and this can be used to cause an input capture interrupt, if this interrupt is enabled. when the icr1 is used as top value (see description of the wgm13:0 bits located in the tccr1a and the tccr1b register), t he icp1 is disconnected, and consequently, the input capture function is disabled. ? bit 5 ? reserved bit this bit is reserved for future use. for ensuring compatibility with future devices, this bit must be written to zero when tccr1b is written. ? bit 4:3 ? wgm13:2: waveform generation mode see tccr1a register description. ? bit 2:0 ? cs12:0: clock select the three clock select bits select the clock source to be used by the timer/counter, see figure 49 and figure 50. if external pin modes are used for the timer/counter1, transitions on the t1 pin will clock the counter even if the pin is configured as an output. this feature allows software control of the counting. bit 7654 3210 icnc1 ices1 ? wgm13 wgm12 cs12 cs11 cs10 tccr1b read/write r/w r/w r r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 49. clock select bit description cs12 cs11 cs10 description 0 0 0 no clock source (timer/counter stopped). 001clk i/o /1 (no prescaling) 010clk i/o /8 (from prescaler) 011clk i/o /64 (from prescaler) 100clk i/o /256 (from prescaler) 101clk i/o /1024 (from prescaler) 1 1 0 external clock source on t1 pin. clock on falling edge. 1 1 1 external clock source on t1 pin. clock on rising edge.
114 atmega8535(l) 2502k?avr?10/06 timer/counter1 ? tcnt1h and tcnt1l the two timer/counter i/o locations (tcnt1h and tcnt1l, combined tcnt1) give direct access, both for read and for write operations, to the timer/counter unit 16-bit counter. to ensure that both the high and low bytes are read and written simultaneously when the cpu accesses these registers, the access is performed using an 8-bit tempo- rary high byte register (temp). this temporar y register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 92. modifying the counter (tcnt1) while the counter is running introduces a risk of missing a compare match between tcnt1 and one of the ocr1x registers. writing to the tcnt1 register blocks (removes) the compare match on the following timer clock for all compare units. output compare register 1 a ? ocr1ah and ocr1al output compare register 1 b ? ocr1bh and ocr1bl the output compare registers contain a 16- bit value that is continuously compared with the counter value (tcnt1). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc1x pin. the output compare registers are 16-bit in size. to ensure that both the high and low bytes are written simultaneously when the cpu writes to these registers, the access is performed using an 8-bit temporary high byte register (temp). this temporary register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 92. input capture register 1 ? icr1h and icr1l the input capture is updated with the counter (tcnt1) value each time an event occurs on the icp1 pin (or optionally on the analog comparator output for timer/counter1). the input capture can be used for defining the counter top value. the input capture register is 16-bit in size. to ensure that both the high and low bytes are read simultaneously when the cpu accesses these registers, the access is per- formed using an 8-bit temporary high byte register (temp). this temporary register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 92. bit 76543210 tcnt1[15:8] tcnt1h tcnt1[7:0] tcnt1l read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ocr1a[15:8] ocr1ah ocr1a[7:0] ocr1al read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ocr1b[15:8] ocr1bh ocr1b[7:0] ocr1bl read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 icr1[15:8] icr1h icr1[7:0] icr1l read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
115 atmega8535(l) 2502k?avr?10/06 timer/counter interrupt mask register ? timsk (1) note: 1. this register contains interrupt control bits for several timer/counters, but only timer1 bits are described in this section. the remaining bits are described in their respective timer sections. ? bit 5 ? ticie1: timer/counter1, input capture interrupt enable when this bit is written to one and the i-flag in the status register is set (interrupts glo- bally enabled), the timer/counter1 input capture interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 46) is executed when the icf1 flag, located in tifr, is set. ? bit 4 ? ocie1a: timer/counter1, output compare a match interrupt enable when this bit is written to one and the i-flag in the status register is set (interrupts glo- bally enabled), the timer/counter1 output compare a match interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 46) is executed when the ocf1a flag, located in tifr, is set. ? bit 3 ? ocie1b: timer/counter1, output compare b match interrupt enable when this bit is written to one and the i-flag in the status register is set (interrupts glo- bally enabled), the timer/counter1 output compare b match interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 46) is executed when the ocf1b flag, located in tifr, is set. ? bit 2 ? toie1: timer/counter1, overflow interrupt enable when this bit is written to one and the i-flag in the status register is set (interrupts glo- bally enabled), the timer/counter1 overflow interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 46) is executed when the tov1 flag, located in tifr, is set. bit 76543210 ocie2 toie2 ticie1 ocie1a ocie1b toie1 ocie0 toie0 timsk read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
116 atmega8535(l) 2502k?avr?10/06 timer/counter interrupt flag register ? tifr (1) note: 1. this register contains flag bits for several timer/counters, but only timer1 bits are described in this section. the remaining bits are described in their respective timer sections. ? bit 5 ? icf1: timer/count er1, input capture flag this flag is set when a capture event occurs on the icp1 pin. when the input capture register (icr1) is set by the wgm13:0 to be used as the top value, the icf1 flag is set when the counter reaches the top value. icf1 is automatically cleared when the input capture interrupt vector is executed. alter- natively, icf1 can be cleared by writing a logic one to its bit location. ? bit 4 ? ocf1a: timer/counter1, output compare a match flag this flag is set in the timer clock cycle a fter the counter (tcnt1) value matches the out- put compare register a (ocr1a). note that a forced output compare (foc 1a) strobe will not set the ocf1a flag. ocf1a is automatically cleared when the output compare match a interrupt vector is executed. alternatively, ocf1a can be cleared by writing a logic one to its bit location. ? bit 3 ? ocf1b: timer/counter1, output compare b match flag this flag is set in the timer clock cycle a fter the counter (tcnt1) value matches the out- put compare register b (ocr1b). note that a forced output compare (foc 1b) strobe will not set the ocf1b flag. ocf1b is automatically cleared when the output compare match b interrupt vector is executed. alternatively, ocf1b can be cleared by writing a logic one to its bit location. ? bit 2 ? tov1: timer/counter1, overflow flag the setting of this flag is dependent of the wgm13:0 bits setting. in normal and ctc modes, the tov1 flag is set when the timer overflows. refer to table 48 on page 112 for the tov1 flag behavior when using another wgm13:0 bit setting. tov1 is automatically cleared when the timer/counter1 overflow interrupt vector is executed. alternatively, tov1 can be cleared by writing a logic one to its bit location. bit 76543210 ocf2 tov2 icf1 ocf1a ocf1b tov1 ocf0 tov0 tifr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
117 atmega8535(l) 2502k?avr?10/06 8-bit timer/counter2 with pwm and asynchronous operation timer/counter2 is a general purpose, single channel, 8-bit timer/counter module. the main features are: ? single channel counter ? clear timer on compar e match (auto reload) ? glitch-free, phase correct pu lse width modulator (pwm) ? frequency generator ? 10-bit clock prescaler ? overflow and compare match in terrupt sources (tov2 and ocf2) ? allows clocking from external 32 khz wa tch crystal independent of the i/o clock overview a simplified block diagram of the 8-bit time r/counter is shown in figure 53. for the actual placement of i/o pins, refer to ?pinout atmega8535? on page 2. cpu accessible i/o registers, including i/o bits and i/o pins , are shown in bold. the device-specific i/o register and bit locations are listed in the ?8-bit timer/counter register description? on page 128. figure 53. 8-bit timer/counter block diagram timer/counter data b u s = tcntn waveform generation ocn = 0 control logic = 0xff top bottom count clear direction tovn (int.req.) ocn (int.req.) synchronization unit ocrn tccrn assrn status flags clk i/o clk asy synchronized status flags asynchronous mode select (asn) tosc1 t/c oscillator tosc2 prescaler clk tn clk i/o
118 atmega8535(l) 2502k?avr?10/06 registers the timer/counter (tcnt2) and output compare register (ocr2) are 8-bit registers. interrupt request (shorten as int.req.) signals are all visible in the timer interrupt flag register (tifr). all interrupts are individually masked with the timer interrupt mask register (timsk). tifr and timsk are not shown in the figure since these registers are shared by other timer units. the timer/counter can be clocked internally, via the prescaler, or asynchronously clocked from the tosc1/2 pins, as detailed later in this section. the asynchronous operation is controlled by the asynchronous status register (assr). the clock select logic block controls which clock source the timer/counter uses to increment (or decre- ment) its value. the timer/counter is inactive when no clock source is selected. the output from the clock select logic is referred to as the timer clock (clk t2 ). the double buffered output compare register (ocr2) is compared with the timer/counter value at all times. the result of the compare can be used by the wave- form generator to generate a pwm or variable frequency output on the output compare pin (oc2). see ?output compare unit? on page 119 for details. the compare match event will also set the compare flag (ocf2) which can be used to generate an output compare interrupt request. definitions many register and bit references in this section are written in general form. a lower case ?n? replaces the timer/counter number, in this case 2. however, when using the register or bit defines in a program, the precise form must be used (i.e., tcnt2 for accessing timer/counter2 counter value and so on). the definitions in table 50 are also used extensively throughout this section. timer/counter clock sources the timer/counter can be clocked by an internal synchronous or an external asynchro- nous clock source. t he clock source clk t2 is by default equal to the mcu clock, clk i/o . when the as2 bit in the assr re gister is written to logic one , the clock source is taken from the timer/counter oscillator connec ted to tosc1 and tosc2. for details on asynchronous operation, see ?asynchronous status regist er ? assr? on page 131. for details on clock sources and prescaler, see ?timer/counter prescaler? on page 134. table 50. definitions bottom the counter reaches the bottom when it becomes zero (0x00). max the counter reaches its maximum when it becomes 0xff (decimal 255). top the counter reaches the top when it becomes equal to the highest value in the count sequence. the top value can be assigned to be the fixed value 0xff (max) or the value stored in the ocr2 register. the assignment is dependent on the mode of operation.
119 atmega8535(l) 2502k?avr?10/06 counter unit the main part of the 8-bit timer/counter is the programmable bi-directional counter unit. figure 54 shows a block diagram of the counter and its surrounding environment. figure 54. counter unit block diagram signal description (internal signals): count increment or decrement tcnt2 by 1. direction selects between increment and decrement. clear clear tcnt2 (set all bits to zero). clk t 2 timer/counter clock. top signalizes that tcnt2 has reached maximum value. bottom signalizes that tcnt2 has reached minimum value (zero). depending on the mode of operation used, the counter is cleared, incremented, or dec- remented at each timer clock (clk t2 ). clk t2 can be generated from an external or internal clock source, selected by the clock select bits (cs22:0). when no clock source is selected (cs22:0 = 0) the timer is stopped. however, the tcnt2 value can be accessed by the cpu, regardless of whether clk t2 is present or not. a cpu write overrides (has priority over) all counter clear or count operations. the counting sequence is determined by the setting of the wgm21 and wgm20 bits located in the timer/counter control register (tccr2). there are close connections between how the counter behaves (counts) and how waveforms are generated on the output compare output oc2. for more details about advanced counting sequences and waveform generation, see ?modes of operation? on page 122. the timer/counter overflow flag (tov2) is set according to the mode of operation selected by the wgm21:0 bits. tov2 can be used for generating a cpu interrupt. output compare unit the 8-bit comparator continuously compares tcnt2 with the output compare register (ocr2). whenever tcnt2 equals ocr2, the comparator signals a match. a match will set the output compare flag (ocf2) at the next timer clock cycle. if enabled (ocie2 = 1), the output compare flag generates an output compare interrupt. the ocf2 flag is automatically cleared when the interrupt is executed. alternatively, the ocf2 flag can be cleared by software by writing a logical one to its i/o bit location. the waveform gen- erator uses the match signal to generate an output according to operating mode set by the wgm21:0 bits and compare output mode (com21:0) bits. the max and bottom sig- nals are used by the waveform generator for handling the special cases of the extreme values in some modes of operation (see ?modes of operation? on page 122). figure 55 shows a block diagram of the output compare unit. data b u s tcntn control logic count tovn (int.req.) top bottom direction clear tosc1 t/c oscillator tosc2 prescaler clk i/o clk tn
120 atmega8535(l) 2502k?avr?10/06 figure 55. output compare unit, block diagram the ocr2 register is double buffered when using any of the pulse width modulation (pwm) modes. for the normal and clear timer on compare (ctc) modes of operation, the double buffering is disabled. the double buffering synchronizes the update of the ocr2 compare register to either top or bottom of the counting sequence. the synchro- nization prevents the occurrence of odd-l ength, non-symmetrical pwm pulses, thereby making the output glitch-free. the ocr2 register access ma y seem complex, but this is not the case. when the dou- ble buffering is enabled, the cpu has access to the ocr2 buffer register, and if double buffering is disabled the cp u will access the ocr2 directly. force output compare in non-pwm waveform generation modes, the match output of the comparator can be forced by writing a one to the force output compare (foc2) bit. forcing compare match will not set the ocf2 flag or reload/c lear the timer, but the oc2 pin will be updated as if a real compare match had occurred (the com21:0 bits settings define whether the oc2 pin is set, cleared or toggled). compare match blocking by tcnt2 write all cpu write operations to the tcnt2 register will block any compare match that occurs in the next timer clock cycle, even when the timer is stopped. this feature allows ocr2 to be initialized to th e same value as tcnt2 without triggering an interrupt when the timer/counter clock is enabled. using the output compare unit since writing tcnt2 in any mode of operat ion will block all compare matches for one timer clock cycle, there are risks involved when changing tcnt2 when using the output compare channel, independently of whether the timer/counter is running or not. if the value written to tcnt2 equa ls the ocr2 value, the compare match will be missed, resulting in incorrect waveform generation . similarly, do not write the tcnt2 value equal to bottom when the counter is down-counting. the setup of the oc2 should be performed before setting the data direction register for the port pin to output. the easiest way of setting the oc2 value is to use the force output compare (foc2) strobe bit in normal mode. the oc2 register keeps its value even when changing between waveform generation modes. ocfn (int.req.) = (8-bit comparator ) ocrn ocxy data b u s tcntn wgmn1:0 waveform generator top focn comn1:0 bottom
121 atmega8535(l) 2502k?avr?10/06 be aware that the com21:0 bits are not double buffered together with the compare value. changing the com21:0 bits will take effect immediately. compare match output unit the compare output mode (com21:0) bits have two functions. the waveform genera- tor uses the com21:0 bits for defining the output compare (oc2) state at the next compare match. also, the com21:0 bits control the oc2 pin output source. figure 56 shows a simplified schematic of the logic affected by the com21:0 bit setting. the i/o registers, i/o bits, and i/o pins in the figur e are shown in bold. only the parts of the general i/o port control regi sters (ddr and port) that are affected by the com21:0 bits are shown. when referring to the oc2 st ate, the reference is for the internal oc2 register, not the oc2 pin. figure 56. compare match output unit, schematic the general i/o port function is overridden by the output compare (oc2) from the waveform generator if either of the com21:0 bits are set. however, the oc2 pin direc- tion (input or output) is still controlled by t he data direction register (ddr) for the port pin. the data direction register bit for the oc2 pin (ddr_oc2) must be set as output before the oc2 value is visible on the pi n. the port override function is independent of the waveform generation mode. the design of the output compare pin logic al lows initialization of the oc2 state before the output is enabled. note that some com21:0 bit settings are reserved for certain modes of operation. see ?8-bit timer/counter register description? on page 128. compare output mode and waveform generation the waveform generator uses the com21:0 bits differently in normal, ctc, and pwm modes. for all modes, setting the com21:0 = 0 tells the waveform generator that no action on the oc2 register is to be performed on the next compare match. for com- pare output actions in the non-pwm modes refer to table 52 on page 129. for fast pwm mode, refer to table 53 on page 129, and for phase correct pwm refer to table 54 on page 130. port ddr dq dq ocn pin ocn dq waveform generator comn1 comn0 0 1 data b u s focn clk i/o
122 atmega8535(l) 2502k?avr?10/06 a change of the com21:0 bits state will take effect at the first compare match after the bits are written. for non-pwm modes, the action can be forced to have an immediate effect by using the foc2 strobe bits. modes of operation the mode of operation (i.e., the behavior of the timer/counter and the output compare pins) is defined by the combination of the waveform generation mode (wgm21:0) and compare output mode (com21:0) bits. the compare output mode bits do not affect the counting sequence, while the waveform generation mode bits do. the com21:0 bits control whether the pwm output generated should be inverted or not (inverted or non-inverted pwm). for non-pwm modes the com21:0 bits control whether the output should be set, cleared, or toggled at a compare match (see ?compare match output unit? on page 121.). for detailed timing information refer to ?timer/counter timing diagrams? on page 126. normal mode the simplest mode of operation is the normal mode (wgm21:0 = 0). in this mode the counting direction is always up (incrementing), and no counter clear is performed. the counter simply overruns when it passes its maximum 8-bit value (top = 0xff) and then restarts from the bottom (0x00). in normal operation the timer/counter overflow flag (tov2) will be set in the same timer cloc k cycle as the tcnt2 becomes zero. the tov2 flag in this case behaves like a ninth bit, except that it is only set, not cleared. however, combined with the timer overflow interrupt that automatically clears the tov2 flag, the timer resolution can be increased by software. there are no special cases to consider in the normal mode, a new counter value can be written anytime. the output compare unit can be used to generate interrupts at some given time. using the output compare to generate waveforms in normal mode is not recommended, since this will occupy too much of the cpu time. clear timer on compare match (ctc) mode in clear timer on compare or ctc mode (wgm21:0 = 2), the ocr2 register is used to manipulate the counter resolution. in ctc mode, the counter is cleared to zero when the counter value (tcnt2) matches the ocr2. the ocr2 defines the top value for the counter, hence also its resolution. this mode allows greater control of the compare match output frequency. it also simplifies th e operation of counting external events. the timing diagram for the ctc mode is shown in figure 57. the counter value (tcnt2) increases until a compare match occurs between tcnt2 and ocr2, and then counter (tcnt2) is cleared. figure 57. ctc mode, timing diagram tcntn ocn (toggle) ocn interrupt flag set 1 4 period 2 3 (comn1:0 = 1)
123 atmega8535(l) 2502k?avr?10/06 an interrupt can be generated each time the counter value reaches the top value by using the ocf2 flag. if the interrupt is enabled, the interrupt handler routine can be used for updating the top value. however, changing the top to a value close to bot- tom when the counter is running with none or a low prescaler value must be done with care since the ctc mode does not have the double buffering feature. if the new value written to ocr2 is lower than the current va lue of tcnt2, the counter will miss the compare match. the counter will then have to count to its maximum value (0xff) and wrap around starting at 0x00 before the compare match can occur. for generating a waveform output in ctc mode, the oc2 output can be set to toggle its logical level on each compare match by setting the compare output mode bits to toggle mode (com21:0 = 1). the oc2 value will not be visible on the port pin unless the data direction for the pin is set to output. the wave form generated will have a maximum fre- quency of f oc2 = f clk_i/o /2 when ocr2 is set to zero (0x00). the waveform frequency is defined by the following equation: the ? n ? variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024). as for the normal mode of operation, the tov2 flag is set in the same timer clock cycle that the counter counts from max to 0x00. fast pwm mode the fast pulse width modulation or fast pwm mode (wgm21:0 = 3) provides a high fre- quency pwm waveform generation option. the fast pwm differs from the other pwm option by its single-slope operation. the counter counts from bottom to max then restarts from bottom. in non-inverting compare output mode, the output compare (oc2) is cleared on the compare match between tcnt2 and ocr2, and set at bot- tom. in inverting compare output mode, the output is set on compare match and cleared at bottom. due to the single-slope operation, the operating frequency of the fast pwm mode can be twice as high as t he phase correct pwm mode that uses dual- slope operation. this high frequency makes the fast pwm mode well suited for power regulation, rectification, and dac applicat ions. high frequency allows physically small sized external components (coils, capacitors), and therefore reduces total system cost. in fast pwm mode, the counter is incremented until the counter value matches the max value. the counter is then cleared at the following timer clock cycle. the timing diagram for the fast pwm mode is shown in figure 58. the tcnt2 value is in the timing diagram shown as a histogram for illustrating the single-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt2 slopes represent compare matches between ocr2 and tcnt2. f ocn f clk_i/o 2 n 1 ocrn + () ?? ---------------------------------------------- - =
124 atmega8535(l) 2502k?avr?10/06 figure 58. fast pwm mode, timing diagram the timer/counter overflow flag (tov2) is set each time the counter reaches max. if the interrupt is enabled, the interrupt handler routine can be used for updating the com- pare value. in fast pwm mode, the compare unit allows generation of pwm waveforms on the oc2 pin. setting the com21:0 bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the com21:0 to three (see table 53 on page 129). the actual oc2 value will onl y be visible on the port pin if the data direction for the port pin is set as output. the pwm waveform is generated by setting (or clearing) the oc2 register at the compare match between ocr2 and tcnt2, and clearing (or set- ting) the oc2 register at the timer clock cycle the counter is cleared (changes from max to bottom). the pwm frequency for the output can be calculated by the following equation: the ? n ? variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024). the extreme values for the ocr2 register represent special cases when generating a pwm waveform output in the fast pwm mode. if the ocr2 is set equal to bottom, the output will be a narrow spike for each max+1 timer clock c ycle. setting the ocr2 equal to max will result in a constantly high or low output (depen ding on the pola rity of the out- put set by the com21:0 bits.) a frequency (with 50% duty cycle) waveform output in fast pwm mode can be achieved by setting oc2 to toggle its logical level on each compare match (com21:0 = 1). the waveform generated will have a maximum frequency of f oc2 = f clk_i/o /2 when ocr2 is set to zero. this feature is similar to the oc2 toggle in ctc mode, except the double buffer feature of the output compare unit is enabled in the fast pwm mode. tcntn ocrn update and tovn interrupt flag set 1 period 2 3 ocn ocn (comn1:0 = 2) (comn1:0 = 3) ocrn interrupt flag set 4 5 6 7 f ocnpwm f clk_i/o n 256 ? ------------------ =
125 atmega8535(l) 2502k?avr?10/06 phase correct pwm mode the phase correct pwm mode (wgm21:0 = 1) provides a high resolution phase correct pwm waveform generation option. the phase correct pwm mode is based on a dual- slope operation. the counter counts repeatedly from bottom to max and then from max to bottom. in non-inverting compare output mode, the output compare (oc2) is cleared on the compare match between tcnt2 and ocr2 while up-counting, and set on the compare match while down-counting. in inverting output compare mode, the operation is inverted. the dual-slope operation has lower maximum operation frequency than single slope operation. however, due to the symmetric feature of the dual-slope pwm modes, these modes are preferred for motor control applications. the pwm resolution for the phase correct pwm mode is fixed to eight bits. in phase correct pwm mode the counter is incremented until the counter value matches max. when the counter reaches max, it change s the count direction. the tcnt2 value will be equal to max for one timer clock cycle. the timing diagram for the phase correct pwm mode is shown on figure 59. the tcnt2 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. the diagra m includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt2 slopes repre- sent compare matches between ocr2 and tcnt2. figure 59. phase correct pwm mode, timing diagram the timer/counter overflow flag (tov2) is set each time the counter reaches bot- tom. the interrupt flag can be used to generate an interrupt each time the counter reaches the bottom value. in phase correct pwm mode, the compare unit allows generation of pwm waveforms on the oc2 pin. setting the com21:0 bits to two will produce a non-inverted pwm. an inverted pwm output can be generated by setting the com21:0 to three (see table 54 on page 130). the act ual oc2 value will only be visible on the port pin if the data direc- tion for the port pin is set as output. the pwm waveform is generated by clearing (or setting) the oc2 register at the compare match between ocr2 and tcnt2 when the counter increments, and setting (or clearing) the oc2 register at compare match tovn interrupt flag set ocn interrupt flag set 1 2 3 tcntn period ocn ocn (comn1:0 = 2) (comn1:0 = 3) ocrn update
126 atmega8535(l) 2502k?avr?10/06 between ocr2 and tcnt2 when the counter decrements. the pwm frequency for the output when using phase correct pwm can be calculated by the following equation: the ? n ? variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024). the extreme values for the ocr2 register represent special cases when generating a pwm waveform output in the phase correct pwm mode. if the ocr2 is set equal to bottom, the output will be cont inuously low and if set e qual to max the output will be continuously high for non-inverted pwm mode. for inverted pw m the output will have the opposite logic values. at the very start of period 2 in figure 59 ocn has a transition from high to low even though there is no compare match. the point of this transition is to guarantee symmetry around bottom. there are two cases that give a transition without compare match. ? ocr2 changes its value from max, like in figure 59. when the ocr2 value is max the ocn pin value is the same as the result of a down-counting compare match. to ensure symmetry around bottom the ocn value at max must correspond to the result of an up-counting compare match. ? the timer starts counting from a value higher than the one in ocr2, and for that reason misses the compare match and hence the ocn change that would have happened on the way up. timer/counter timing diagrams the following figures show the timer/c ounter in synchronous mode, and the timer clock (clk t2 ) is therefore shown as a clock enabl e signal. in asynchronous mode, clk i/o should be replaced by the timer/counter oscillator clock. the figures include informa- tion on when interrupt flags are set. figure 60 contains timing data for basic timer/counter operation. the figure shows the count sequence close to the max value in all modes other than phase correct pwm mode. figure 60. timer/counter timing diagram, no prescaling figure 61 shows the same timing data, but with the prescaler enabled. f ocnpcpwm f clk_i/o n 510 ? ------------------ = clk tn (clk i/o /1) tovn clk i/o tcntn max - 1 max bottom bottom + 1
127 atmega8535(l) 2502k?avr?10/06 figure 61. timer/counter timing diagram, with prescaler (f clk_i/o /8) figure 62 shows the setting of ocf2 in all modes except ctc mode. figure 62. timer/counter timing diagram, setting of ocf2, with prescaler (f clk_i/o /8) figure 63 shows the setting of ocf2 and the clearing of tcnt2 in ctc mode. tovn tcntn max - 1 max bottom bottom + 1 clk i/o clk tn (clk i/o /8) ocfn ocrn tcntn ocrn value ocrn - 1 ocrn ocrn + 1 ocrn + 2 clk i/o clk tn (clk i/o /8)
128 atmega8535(l) 2502k?avr?10/06 figure 63. timer/counter timing diagram, clear timer on compare match mode, with prescaler (f clk_i/o /8) 8-bit timer/counter register description timer/counter control register ? tccr2 ? bit 7 ? foc2: force output compare the foc2 bit is only active when the wgm bits specify a non-pwm mode. however, for ensuring compatibility with future devices, th is bit must be set to zero when tccr2 is written when operating in pwm mode. when writing a logical one to the foc2 bit, an immediate compare match is forced on the waveform generation unit. the oc2 output is changed according to its com21:0 bits setting. note that the foc2 bit is implemented as a strobe. therefore it is the value present in the com21:0 bits that determines the effect of the forced compare. a foc2 strobe will not generate any interr upt, nor will it clear the timer in ctc mode using ocr2 as top. the foc2 bit is always read as zero. ? bit 6, 3 ? wgm21:0: waveform generation mode these bits control the counting sequence of the counter, the source for the maximum (top) counter value, and what type of waveform generation to be used. modes of oper- ation supported by the timer/counter unit are: normal mode, clear timer on compare match (ctc) mode, and two types of pulse width modulation (pwm) modes. see table 51 and ?modes of operation? on page 122. ocfn ocrn tcntn (ctc) top top - 1 top bottom bottom + 1 clk i/o clk tn (clk i/o /8) bit 76543210 foc2 wgm20 com21 com20 wgm21 cs22 cs21 cs20 tccr2 read/write w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
129 atmega8535(l) 2502k?avr?10/06 note: 1. the ctc2 and pwm2 bit definition names are now obsolete. use the wgm21:0 def- initions. however, the functionality and loca tion of these bits are compatible with previous versions of the timer. ? bit 5:4 ? com21:0: compare match output mode these bits control the output compare pin (oc2) behavior. if one or both of the com21:0 bits are set, the oc2 output overrides the normal port functionality of the i/o pin it is connected to. however, note that t he data direction register (ddr) bit corre- sponding to oc2 pin must be set in order to enable the output driver. when oc2 is connected to the pin, the function of the com21:0 bits depends on the wgm21:0 bit setting. table 52 shows the com21:0 bit functionality when the wgm21:0 bits are set to a normal or ctc mode (non-pwm). table 53 shows the com21:0 bit functionality when the wgm21:0 bits are set to fast pwm mode. note: 1. a special case occurs when ocr2 equals top and com21 is set. in this case, the compare match is ignored, but the set or clear is done at top. see ?fast pwm mode? on page 123 for more details. table 51. waveform generation mode bit description (1) mode wgm21 (ctc2) wgm20 (pwm2) timer/counter mode of operation top update of ocr2 tov2 flag set on 0 0 0 normal 0xff immediate max 1 0 1 pwm, phase correct 0xff top bottom 2 1 0 ctc ocr2 immediate max 3 1 1 fast pwm 0xff bottom max table 52. compare output mode, non-pwm mode com21 com20 description 0 0 normal port operation, oc2 disconnected. 0 1 toggle oc2 on compare match. 1 0 clear oc2 on compare match. 1 1 set oc2 on compare match. table 53. compare output mode, fast pwm mode (1) com21 com20 description 0 0 normal port operation, oc2 disconnected. 01reserved 1 0 clear oc2 on compare match, set oc2 at top (non-inverting). 1 1 set oc2 on compare match, clear oc2 at top (inverting).
130 atmega8535(l) 2502k?avr?10/06 table 54 shows the com21:0 bit functionality when the wgm21:0 bits are set to phase correct pwm mode. note: 1. a special case occurs when ocr2 equals top and com21 is set. in this case, the compare match is ignored, but the set or clear is done at top. see ?phase correct pwm mode? on page 125 for more details. ? bit 2:0 ? cs22:0: clock select the three clock select bits select the clock so urce to be used by the timer/counter, see table 55. timer/counter register ? tcnt2 the timer/counter register gives direct access, both for read and write operations, to the timer/counter unit 8-bit counter. writing to the tcnt2 register blocks (removes) the compare match on the following timer clock. modifying the counter (tcnt2) while the counter is running, introduces a risk of missing a compare match between tcnt2 and the ocr2 register. table 54. compare output mode, phase correct pwm mode (1) com21 com20 description 0 0 normal port operation, oc2 disconnected. 01reserved 1 0 clear oc2 on compare match when up-counting. set oc2 on compare match when down-counting. 1 1 set oc2 on compare match when up-counting. clear oc2 on compare match when down-counting. table 55. clock select bit description cs22 cs21 cs20 description 0 0 0 no clock source (timer/counter stopped). 001 clk t2s /(no prescaling) 010 clk t2s /8 (from prescaler) 011 clk t2s /32 (from prescaler) 100 clk t2s /64 (from prescaler) 101 clk t2s /128 (from prescaler) 110clk t 2 s /256 (from prescaler) 111clk t 2 s /1024 (from prescaler) bit 76543210 tcnt2[7:0] tcnt2 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
131 atmega8535(l) 2502k?avr?10/06 output compare register ? ocr2 the output compare register contains an 8-bit value that is continuously compared with the counter value (tcnt2). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc2 pin. asynchronous operation of the timer/counter asynchronous status register ? assr ? bit 3 ? as2: asynchronous timer/counter2 when as2 is written to zero, timer/count er2 is clocked from the i/o clock, clk i/o . when as2 is written to one, timer/counter2 is cl ocked from a crystal oscillator connected to the timer oscillator1 (tosc1) pin. when t he value of as2 is changed, the contents of tcnt2, ocr2, and tccr2 might be corrupted. ? bit 2 ? tcn2ub: timer/counter2 update busy when timer/counter2 operates asynchronous ly and tcnt2 is written, this bit becomes set. when tcnt2 has been updated from the temporary storage register, this bit is cleared by hardware. a logica l zero in this bit indicate s that tcnt2 is ready to be updated with a new value. ? bit 1 ? ocr2ub: output comp are register 2 update busy when timer/counter2 operates asynchronously and ocr2 is written, this bit becomes set. when ocr2 has been updated from the temporary storage register, this bit is cleared by hardware. a logical zero in this bit indicates that ocr2 is ready to be updated with a new value. ? bit 0 ? tcr2ub: timer/counter control register 2 update busy when timer/counter2 operates asynchronously and tccr2 is written, this bit becomes set. when tccr2 has been updated from the temporary storage register, this bit is cleared by hardware. a logical zero in this bit indicates that tccr2 is ready to be updated with a new value. if a write is performed to any of the three timer/counter2 registers while its update busy flag is set, the updated value might get corrupted and cause an unintentional inter- rupt to occur. the mechanisms for reading tcnt2, ocr2, and tccr2 are different. when reading tcnt2, the actual timer value is read. when reading ocr2 or tccr2, the value in the temporary storage register is read. bit 76543210 ocr2[7:0] ocr2 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543 2 1 0 ? ? ? ? as2 tcn2ub ocr2ub tcr2ub assr read/writerrrrr/wr r r initial value 0 0 0 0 0 0 0 0
132 atmega8535(l) 2502k?avr?10/06 asynchronous operation of timer/counter2 when timer/counter2 operates asynchronously, some considerations must be taken. ? warning: when switching between asynchronous and synchronous clocking of timer/counter2 , the timer registers tcnt2, ocr2 , and tccr2 might be corrupted. a safe procedure for switching clock source is: 1. disable the timer/counter2 interrupts by clearing ocie2 and toie2. 2. select clock source by setting as2 as appropriate. 3. write new values to tcnt2, ocr2, and tccr2. 4. to switch to asynchronous operation: wait for tcn2ub, ocr2ub, and tcr2ub. 5. clear the timer/counter2 interrupt flags. 6. enable interrupts, if needed. ? the oscillator is optimized for use wit h a 32.768 khz watch crystal. applying an external clock to the tosc1 pin may result in incorrect timer/counter2 operation. the cpu main clock frequency must be more than four times the oscillator frequency. ? when writing to one of the registers tcnt2, ocr2, or tccr2, the value is transferred to a temporary register, and latched after two positive edges on tosc1. the user should not write a new value before the contents of the temporary register have been transferred to its destination. each of the three mentioned registers have their individual temporary register, which means that, e.g., writing to tcnt2 does not disturb an ocr2 write in progress. to detect that a transfer to the destination register has taken place, the asynchronous status re gister ? assr ? has been implemented. ? when entering power-save or extended standby mode after having written to tcnt2, ocr2, or tccr2, the user must wait until the written register has been updated if timer/ counter2 is used to wake up th e device. otherwise, the mcu will enter sleep mode before the changes are effective. this is particularly important if the output compare 2 interrupt is used to wake up the device, since the output compare function is disabled during writing to ocr2 or tcnt2. if the write cycle is not finished, and the mcu enters sleep mode before the ocr2ub bit returns to zero, the device will never receive a comp are match interrupt, and the mcu will not wake up. ? if timer/counter2 is used to wake the device up from power-save or extended standby mode, precautions must be taken if the user wants to re-enter one of these modes: the interrupt logic needs one tosc1 cycle to be reset. if the time between wake-up and re-entering sleep mode is less than one tosc1 cycle, the interrupt will not occur, and the device will fail to wake up. if the user is in do ubt whether the time before re-entering power-save or extended standby mode is sufficient, the following algorithm can be used to ensure that one tosc1 cycle has elapsed: 1. write a value to tc cr2, tcnt2, or ocr2. 2. wait until the corresponding update busy flag in assr returns to zero. 3. enter power-save or extended standby mode. ? when the asynchronous operation is se lected, the 32.768 khz oscillator for timer/counter2 is always running, except in power-down and standby modes. after a power-up reset or wake-up from power-down or standby mode, the user should be aware of the fact that this oscillator mi ght take as long as one second to stabilize. the user is advised to wait for at least one second before using timer/counter2 after power-up or wake-up from power-down or standby mode. the contents of all timer/counter2 registers must be considered lost after a wake-up from power-
133 atmega8535(l) 2502k?avr?10/06 down or standby mode due to unstable clock signal upon start-up, no matter whether the oscillator is in use or a cl ock signal is applied to the tosc1 pin. ? description of wake-up from power-save or extended standby mode when the timer is clocked asynchronously: when the interrupt condition is met, the wake up process is started on the following cycle of the timer clock, that is, the timer is always advanced by at least one before the processor can read the counter value. after wake-up, the mcu is halted for four cycles, it executes the interrupt routine, and resumes execution from the instruction following sleep. ? reading of the tcnt2 register shortly after wake-up from power-save may give an incorrect result. since tcnt2 is clocked on the asynchronous tosc clock, reading tcnt2 must be done through a register synchronized to the internal i/o clock domain. synchronization takes place for every rising tosc1 edge. when waking up from power-save mode, and the i/o clock (clk i/o ) again becomes active, tcnt2 will read as the previous value (before entering sleep) until the next rising tosc1 edge. the phase of the tosc clock after waking up from power-save mode is essentially unpredictable, as it depends on the wake-up time. the recommended procedure for reading tcnt2 is thus as follows: 1. write any value to either of the registers ocr2 or tccr2. 2. wait for the corresponding update busy flag to be cleared. 3. read tcnt2. ? during asynchronous operation, the synchronization of the interrupt flags for the asynchronous timer takes thr ee processor cycles plus one timer cycle. the timer is therefore advanced by at least one before the processor can read the timer value causing the setting of the interrupt flag. the output compare pin is changed on the timer clock and is not synchronized to the processor clock. timer/counter interrupt mask register ? timsk ? bit 7 ? ocie2: timer/counter2 output compare match interrupt enable when the ocie2 bit is written to one and the i- bit in the status register is set (one), the timer/counter2 compare match interrupt is enabled. the corresponding interrupt is executed if a compare match in timer/counter2 occurs (i.e., when the ocf2 bit is set in the timer/counter interrupt flag register ? tifr). ? bit 6 ? toie2: timer/counter2 overflow interrupt enable when the toie2 bit is written to one and the i- bit in the status register is set (one), the timer/counter2 overflow interrupt is enable d. the corresponding interrupt is executed if an overflow in timer/counter2 occurs (i.e., when the tov2 bit is set in the timer/counter interrupt flag register ? tifr). bit 76543210 ocie2 toie2 ticie1 ocie1a ocie1b toie1 ocie0 toie0 timsk read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
134 atmega8535(l) 2502k?avr?10/06 timer/counter interrupt flag register ? tifr ? bit 7 ? ocf2: output compare flag 2 the ocf2 bit is set (one) when a compar e match occurs between the timer/counter2 and the data in ocr2 ? output compare register 2. ocf2 is cleared by hardware when executing the corresponding interrup t handling vector. alternatively, ocf2 is cleared by writing a logic one to the flag. when the i-bit in sreg, ocie2 (timer/counter2 compare match interrupt enable), and ocf2 are set (one), the timer/counter2 compare match interrupt is executed. ? bit 6 ? tov2: timer/counter2 overflow flag the tov2 bit is set (one) when an overflow occurs in timer/counter2. tov2 is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, tov2 is cleared by writing a logic one to the flag. when the sreg i-bit, toie2 (timer/counter2 overflow interrupt enable), and tov2 are set (one), the timer/counter2 overflow interrupt is executed. in pwm mode, this bit is set when timer/counter2 changes counting direction at 0x00. timer/counter prescaler figure 64. prescaler for timer/counter2 the clock source for timer/counter2 is named clk t2s . clk t2s is, by default, connected to the main system i/o clock clk i o . by setting the as2 bit in assr , timer/counter2 is asyn- chronously clocked from the tosc1 pin. th is enables use of timer/counter2 as a real time counter (rtc). when as2 is set, pins tosc1 and tosc2 are disconnected from port c. a crystal can then be connected between the tosc1 and tosc2 pins to serve as an independent clock source for timer/counter2. the oscillator is optimized for use with a 32.768 khz crystal. applying an ex ternal clock source to tosc1 is not recommended. for timer/counter2, the possible prescaled selections are: clk t2s /8, clk t2s /32, clk t2s /64, clk t2s /128, clk t2s /256, and clk t2s /1024. additionally, clk t2s as well as 0 (stop) may be selected. setting the psr2 bit in sfior rese ts the prescaler. this allows the user to operate with a predictable prescaler. bit 76543210 ocf2 tov2 icf1 ocf1a ocf1b tov1 ocf0 tov0 tifr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 10-bit t/c prescaler timer/counter2 clock source clk i/o clk t2s tosc1 as2 cs20 cs21 cs22 clk t2s /8 clk t2s /64 clk t2s /128 clk t2s /1024 clk t2s /256 clk t2s /32 0 psr2 clear clk t2
135 atmega8535(l) 2502k?avr?10/06 special function io register ? sfior ? bit 1 ? psr2: prescaler reset timer/counter2 when this bit is written to one, the timer/ counter2 prescaler will be reset. the bit will be cleared by hardware after the operation is pe rformed. writing a zero to this bit will have no effect. this bit will always be read as zero if timer/counter2 is clocked by the internal cpu clock. if this bit is written when timer/counter2 is operating in asynchronous mode, the bit will remain one unt il the prescaler has been reset. bit 7 6 5 4 3 2 1 0 adts2 adts1 adts0 ? acme pud psr2 psr10 sfior read/write r/w r/w r/w r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
136 atmega8535(l) 2502k?avr?10/06 serial peripheral interface ? spi the serial peripheral interface (spi) allows high-speed synchronous data transfer between the atmega8535 and peripheral devices or between several avr devices. the atmega8535 spi includes the following features: ? full duplex, three-wire synchronous data transfer ? master or slave operation ? lsb first or msb first data transfer ? seven programmable bit rates ? end of transmission interrupt flag ? write collision flag protection ? wake-up from idle mode ? double speed (ck/2) master spi mode figure 65. spi block diagram (1) note: 1. refer to figure 1 on page 2, and table 26 on page 60 for spi pin placement. the interconnection between master and slav e cpus with spi is shown in figure 66. the system consists of two shift registers, and a master clock g enerator. the spi mas- ter initiates the communication cycle when pulling low the slave select ss pin of the desired slave. master and slave prepare the data to be sent in their respective shift registers, and the master generates the required clock pulses on the sck line to inter- change data. data is always shifted from master to slave on the master out ? slave in, mosi, line, and from slave to master on the master in ? slave out, miso, line. after each data packet, the master will synchronize the slave by pulling high the slave select, ss , line. when configured as a master, the spi interface has no automatic control of the ss line. this must be handled by user software before communication can start. when this is spi2x spi2x divider /2/4/8/16/32/64/128
137 atmega8535(l) 2502k?avr?10/06 done, writing a byte to the spi data register starts the spi clock generator, and the hardware shifts the eight bits into the slave. after shifting one byte, the spi clock gener- ator stops, setting the end of transmission fl ag (spif). if the spi interrupt enable bit (spie) in the spcr register is set, an interrupt is requested. the master may continue to shift the next byte by writing it into spdr, or signal the end of packet by pulling high the slave select, ss line. the last incoming byte will be kept in the buffer register for later use. when configured as a slave, the spi interf ace will remain sleeping with miso tri-stated as long as the ss pin is driven high. in this state, software may update the contents of the spi data register, spdr, but the data will not be shifted out by incoming clock pulses on the sck pin until the ss pin is driven low. as one byte has been completely shifted, the end of transmission flag, spif is set. if the spi interrupt enable bit, spie, in the spcr register is set, an interrupt is requested. the slave may continue to place new data to be sent into spdr before reading the incoming data. the last incoming byte will be kept in the buffer register for later use. figure 66. spi master-slave interconnection the system is single buffered in the transmit direction and double buffered in the receive direction. this means that bytes to be tr ansmitted cannot be written to the spi data register before the entire shift cycle is completed. when receiving data, however, a received character must be read from the spi data register before the next character has been completely shifted in. otherwise, the first byte is lost. in spi slave mode, the control logic will sample the incoming signal of the sck pin. to ensure correct sampling of the clock signal , the minimum low and high periods should be: low periods: longer than 2 cpu clock cycles. high periods: longer than 2 cpu clock cycles. when the spi is enabled, the data direction of the mosi, miso, sck, and ss pins is overridden according to table 56 on page 138. for more details on automatic port over- rides, refer to ?alternate port functions? on page 57. msb master lsb 8 bit shift register msb slave lsb 8 bit shift register miso mosi spi clock generator sck ss miso mosi sck ss v cc shift enable
138 atmega8535(l) 2502k?avr?10/06 note: 1. see ?alternate functions of port b? on page 60 for a detailed description of how to define the direction of the user defined spi pins. the following code examples show how to initialize the spi as a master and how to per- form a simple transmission. ddr_spi in the ex amples must be replaced by the actual data direction register controlling the spi pins. dd_mosi, dd_miso and dd_sck must be replaced by the actual data direction bits for these pins. for example, if mosi is placed on pin pb5, replace dd_mosi with ddb5, and ddr_spi with ddrb. table 56. spi pin overrides (1) pin direction, master spi direction, slave spi mosi user defined input miso input user defined sck user defined input ss user defined input assembly code example (1)
139 atmega8535(l) 2502k?avr?10/06 note: 1. see ?about code examples? on page 7. spi_masterinit: ; set mosi and sck output, all others input ldi r17,(1< 140 atmega8535(l) 2502k?avr?10/06 the following code examples show how to in itialize the spi as a slave and how to per- form a simple reception. note: 1. see ?about code examples? on page 7. assembly code example (1) spi_slaveinit: ; set miso output, all others input ldi r17,(1< 141 atmega8535(l) 2502k?avr?10/06 ss pin functionality slave mode when the spi is configured as a slave, the slave select (ss ) pin is always input. when ss is held low, the spi is activated, and miso becomes an output if configured so by the user. all other pins are inputs. when ss is driven high, all pins are inputs, and the spi is passive, which means that it will no t receive incoming data. note that the spi logic will be reset once the ss pin is driven high. the ss pin is useful for packet/byte synchronization to keep the slave bit counter syn- chronous with the master clock generator. when the ss pin is driven high, the spi slave will immediately reset the send and receive logi c, and drop any partially received data in the shift register. master mode when the spi is configured as a master (mstr in spcr is set), the user can determine the direction of the ss pin. if ss is configured as an output, the pin is a general output pin which does not affect the spi system. typically, the pin will be driving the ss pin of the spi slave. if ss is configured as an input, it must be held high to ensure master spi operation. if the ss pin is driven low by peripheral circuitry when the spi is configured as a master with the ss pin defined as an input, the spi system interprets this as another master selecting the spi as a slave and starting to send data to it. to avoid bus contention, the spi system takes the following actions: 1. the mstr bit in spcr is cleared and the spi system becomes a slave. as a result of the spi becoming a slave, the mosi and sck pins become inputs. 2. the spif flag in spsr is set, and if the spi interrupt is enab led, and the i-bit in sreg is set, the interrup t routine will be executed. thus, when interrupt-driven spi transmission is used in master mode, and there exists a possibility that ss is driven low, the interrupt shoul d always check that the mstr bit is still set. if the mstr bit has been cleared by a sl ave select, it must be set by the user to re-enable spi master mode. spi control register ? spcr ? bit 7 ? spie: spi interrupt enable this bit causes the spi interrupt to be execut ed if spif bit in the spsr register is set and the if the global interrupt enable bit in sreg is set. ? bit 6 ? spe: spi enable when the spe bit is written to one, the spi is enabled. this bit must be set to enable any spi operations. ? bit 5 ? dord: data order when the dord bit is written to one, the lsb of the data word is transmitted first. when the dord bit is written to zero, the msb of the data word is transmitted first. ? bit 4 ? mstr: master/slave select this bit selects master spi mode when written to one, and slave spi mode when written logic zero. if ss is configured as an i nput and is driven low while mstr is set, mstr will bit 76543210 spie spe dord mstr cpol cpha spr1 spr0 spcr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
142 atmega8535(l) 2502k?avr?10/06 be cleared, and spif in spsr will become set. the user will then have to set mstr to re-enable spi master mode. ? bit 3 ? cpol: clock polarity when this bit is written to one, sck is high when idle. when cpol is written to zero, sck is low when idle. refer to figure 67 and figure 68 for an example. the cpol func- tionality is summarized below: ? bit 2 ? cpha: clock phase the settings of the clock phase bit (cpha) determine if data is sampled on the leading (first) or trailing (last) edge of sck. refer to figure 67 and figure 68 for an example. the cpol functionality is summarized below: ? bits 1, 0 ? spr1, spr0: spi clock rate select 1 and 0 these two bits control the sck rate of the device configured as a master. spr1 and spr0 have no effect on the slave. the relationship between sck and the oscillator clock frequency f osc is shown in the following table: table 57. cpol functionality cpol leading edge trailing edge 0 rising falling 1 falling rising table 58. cpha functionality cpha leading edge trailing edge 0 sample setup 1 setup sample table 59. relationship between sck an d the oscillator frequency spi2x spr1 spr0 sck frequency 000 f osc / 4 001 f osc / 16 010 f osc / 64 011 f osc / 128 100 f osc / 2 101 f osc / 8 110 f osc / 32 111 f osc / 64
143 atmega8535(l) 2502k?avr?10/06 spi status register ? spsr ? bit 7 ? spif: spi interrupt flag when a serial transfer is complete, the spif flag is set. an interrupt is generated if spie in spcr is set and global interrupts are enabled. if ss is an input and is driven low when the spi is in master mo de, this will also set the sp if flag. spif is cleared by hardware when executing the corresponding in terrupt handling vector. alternatively, the spif bit is cleared by first reading the spi status register with spif set, then accessing the spi data register (spdr). ? bit 6 ? wcol: write collision flag the wcol bit is set if the spi data regist er (spdr) is written during a data transfer. the wcol bit (and the spif bit) are clear ed by first reading the spi status register with wcol set, and then accessing the spi data register. ? bit 5..1 ? res: reserved bits these bits are reserved bits in the atmega8535 and will always read as zero. ? bit 0 ? spi2x: double spi speed bit when this bit is written logic one the spi speed (sck frequen cy) will be doubled when the spi is in master mode (see table 59). this means that the minimum sck period will be two cpu clock periods. when the spi is configured as slave, the spi is only guaran- teed to work at f osc /4 or lower. the spi interface on the atmega8535 is also used for program memory and eeprom downloading or uploading. see page 251 for serial programming and verification. spi data register ? spdr the spi data register is a read/write register used for data transfer between the regis- ter file and the spi shift register. writing to the register initiates data transmission. reading the register causes the shift register receive buffer to be read. bit 76543210 spif wcol ? ? ? ? ? spi2x spsr read/writerrrrrrrr/w initial value00000000 bit 76543210 msb lsb spdr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value x x x x x x x x undefined
144 atmega8535(l) 2502k?avr?10/06 data modes there are four combinations of sck phase and polarity with respect to serial data, which are determined by control bits cpha and cpol. the spi data transfer formats are shown in figure 67 and figure 68. data bits are shifted out and latched in on oppo- site edges of the sck signal, en suring sufficient time for dat a signals to stabilize. this is clearly seen by summarizing table 57 and table 58, as done below: figure 67. spi transfer format with cpha = 0 figure 68. spi transfer format with cpha = 1 table 60. cpol functionality leading edge trailing edge spi mode cpol=0, cpha=0 sample (rising) setup (falling) 0 cpol=0, cpha=1 setup (rising) sample (falling) 1 cpol=1, cpha=0 sample (falling) setup (rising) 2 cpol=1, cpha=1 setup (falling) sample (rising) 3 bit 1 bit 6 lsb msb sck (cpol = 0) mode 0 sample i mosi/miso change 0 mosi pin change 0 miso pin sck (cpol = 1) mode 2 ss msb lsb bit 6 bit 1 bit 5 bit 2 bit 4 bit 3 bit 3 bit 4 bit 2 bit 5 msb first (dord = 0) lsb first (dord = 1) sck (cpol = 0) mode 1 sample i mosi/miso change 0 mosi pin change 0 miso pin sck (cpol = 1) mode 3 ss msb lsb bit 6 bit 1 bit 5 bit 2 bit 4 bit 3 bit 3 bit 4 bit 2 bit 5 bit 1 bit 6 lsb msb msb first (dord = 0) lsb first (dord = 1)
145 atmega8535(l) 2502k?avr?10/06 usart the universal synchronous and asynchronous serial receiver and transmitter (usart) is a highly flexible serial communication device. the main features are: ? full duplex operation (i ndependent serial receive and transmit registers) ? asynchronous or synchronous operation ? master or slave clocked synchronous operation ? high resolution baud rate generator ? supports serial frames with 5, 6, 7, 8, or 9 data bits and 1 or 2 stop bits ? odd or even parity generation and parity check supported by hardware ? data overrun detection ? framing error detection ? noise filtering includes false start bit detection and digital low pass filter ? three separate interrupts on tx complete , tx data register empty and rx complete ? multi-processor communication mode ? double speed asynchronous communication mode overview a simplified block diagram of the usart tran smitter is shown in figure 69. cpu acces- sible i/o registers and i/o pins are shown in bold. figure 69. usart block diagram (1) note: 1. refer to figure 1 on page 2, table 34 on page 66, and table 28 on page 62 for usart pin placement. parity generator ubrr[h:l] udr (transmit) ucsra ucsrb ucsrc baud rate generator transmit shift register receive shift register rxd txd pin control udr (receive) pin control xck data recovery clock recovery pin control tx control rx control parity checker data bus osc sync logic clock generator transmitter receiver
146 atmega8535(l) 2502k?avr?10/06 the dashed boxes in the block diagram separate the three main parts of the usart (listed from the top): clock generator, transmitter and receiver. control registers are shared by all units. the clock generation logic consists of synchronization logic for exter- nal clock input used by synchronous slave operation, and the baud rate generator. the xck (transfer clock) pin is only used by synchronous transfer mode. the transmitter consists of a single write buffer, a serial shift register, parity generator and control logic for handling different serial frame formats. the write buffer allows a continuous transfer of data without any delay between frames. the receiver is the most complex part of the usart module due to its clock and data recovery units. the recovery units are used for asynchronous data reception. in addition to the recovery units, the receiver includes a parity checker, control logic, a shift register and a two level receive buffer (udr). the receiver supports the same frame formats as the transmitter, and can detect frame error, data overrun and parity errors. avr usart vs. avr uart ? compatibility the usart is fully compatible with the avr uart regarding: ? bit locations inside all usart registers ? baud rate generation ? transmitter operation ? transmit buffer functionality ? receiver operation however, the receive buffering has two improvements that will affect the compatibility in some special cases: ? a second buffer register has been added. the two buffer registers operate as a circular fifo buffer. therefore the udr must only be read once for each incoming data! more important is the fact that the error flags (fe and dor) and the ninth data bit (rxb8) are buffered with the data in the receive buffer. therefore the status bits must always be read before the udr register is read. otherwise the error status will be lost since the buffer state is lost. ? the receiver shift register can now act as a third buffer level. this is done by allowing the received data to remain in the serial shift register (see figure 69) if the buffer registers are full, until a new start bit is detected. the usart is therefore more resistant to data overrun (dor) error conditions. the following control bits have changed name, but have same functionality and register location: ? chr9 is changed to ucsz2 ? or is changed to dor clock generation the clock generation logic generates the base clock for the transmitter and receiver. the usart supports four modes of clock operation: normal asynchronous, double speed asynchronous, master synchronous and slave synchronous mode. the umsel bit in usart control and status regist er c (ucsrc) selects between asynchronous and synchronous operation. double speed (asynchronous mode only) is controlled by the u2x found in the ucsra register. when using synchronous mode (umsel = 1), the data direction register for the xck pin (ddr_xck) controls whether the clock source is internal (master mode) or external (slave mode). the xck pin is only active when using synchronous mode. figure 70 shows a block diagram of the clock generation logic.
147 atmega8535(l) 2502k?avr?10/06 figure 70. clock generation logic, block diagram signal description: txclk transmitter clock (internal signal). rxclk receiver base clock (internal signal). xcki input from xck pin (internal signal). used for synchronous slave operation. xcko clock output to xck pin (internal signal). used for synchronous master operation. fosc xtal pin frequency (system clock). internal clock generation ? the baud rate generator internal clock generation is used for the asynchronous and the synchronous master modes of operation. the description in this section refers to figure 70. the usart baud rate register (ubrr) and the down-counter connected to it function as a programmable prescaler or baud rate generator. the down-counter, running at sys- tem clock (fosc), is loaded with the ubrr value each time the counter has counted down to zero or when the ubrrl register is written. a clock is generated each time the counter reaches zero. this clock is the baud rate generator clock output (= fosc/(ubrr+1)). the transmitter divides the baud rate generator clock output by 2, 8, or 16 depending on mode. the baud rate generator output is used directly by the receiver?s clock and data recovery units. however, the recovery units use a state machine that uses 2, 8, or 16 states depending on mode set by the state of the umsel, u2x and ddr_xck bits. table 61 contains equations for calculating the baud rate (in bits per second) and for calculating the ubrr value for each mode of operation using an internally generated clock source. prescaling down-counter / 2 ubrr / 4 / 2 fosc ubrr+1 sync register osc xck pin txclk u2x umsel ddr_xck 0 1 0 1 xcki xcko ddr_xck rxclk 0 1 1 0 edge detector ucpol
148 atmega8535(l) 2502k?avr?10/06 note: 1. the baud rate is defined to be the transfer rate in bit per second (bps). baud baud rate (in bits per second, bps) f osc system oscillator clock frequency ubrr contents of the ubrrh and ubrrl registers, (0 - 4095) some examples of ubrr values for some system clock frequencies are found in table 69 (see page 170). double speed operation (u2x) the transfer rate can be doubled by setting t he u2x bit in ucsra. setting this bit only has effect for the asynchronous operation. set this bit to zero when using synchronous operation. setting this bit will reduce the divisor of the baud rate di vider from 16 to 8, effectively doubling the transfer rate for asynchronous communication. note however that the receiver will in this case only use half the number of samples (reduced from 16 to 8) for data sampling and clock recovery, and therefore a more accurate baud rate setting and system clock are required when this mode is used. for the transmitter, there are no downsides. external clock external clocking is used by the synchron ous slave modes of operation. the description in this section refers to figure 70 for details. external clock input from the xck pin is sa mpled by a synchronization register to mini- mize the chance of meta-stability. the output from the synchronization register must then pass through an edge detector before it can be used by the transmitter and receiver. this process introduces a two cp u clock period delay and therefore the max- imum external xck clock frequency is limited by the following equation: note that f osc depends on the stability of the system clock source. it is therefore recom- mended to add some margin to avoid possible loss of data due to frequency variations. table 61. equations for calculating baud rate register setting operating mode equation for calculating baud rate (1) equation for calculating ubrr value asynchronous normal mode (u2x = 0) asynchronous double speed mode (u2x = 1) synchronous master mode baud f osc 16 ubrr 1 + () -------------------------------------- - = ubrr f osc 16 baud ----------------------- - 1 ? = baud f osc 8 ubrr 1 + () ----------------------------------- = ubrr f osc 8 baud -------------------- 1 ? = baud f osc 2 ubrr 1 + () ----------------------------------- = ubrr f osc 2 baud -------------------- 1 ? = f xck f osc 4 ----------- <
149 atmega8535(l) 2502k?avr?10/06 synchronous clock operation when synchronous mode is used (umsel = 1) , the xck pin will be used as either clock input (slave) or clock output (master). the dependency between the clock edges and data sampling or data change is the same. t he basic principle is that data input (on rxd) is sampled at the opposite xck clock edge of the edge the data output (txd) is changed. figure 71. synchronous mode xck timing the ucpol bit ucrsc selects which xck cloc k edge is used for data sampling and which is used for data change. as figure 71 shows, when ucpol is zero the data will be changed at rising xck edge and sampled at falling xck edge. if ucpol is set, the data will be changed at falling xck edge and sample d at rising xck edge. frame formats a serial frame is defined to be one character of data bits with synchronization bits (start and stop bits), and optionally a parity bit fo r error checking. the usart accepts all 30 combinations of the following as valid frame formats: ? 1 start bit ? 5, 6, 7, 8, or 9 data bits ? no even or odd parity bit ? 1 or 2 stop bits a frame starts with the start bit followed by the least significant data bit. then the next data bits, up to a total of nine, are succeeding, ending with the most significant bit. if enabled, the parity bit is inserted after the data bits, before the stop bits. when a com- plete frame is transmitted, it can be dire ctly followed by a new frame, or the communication line can be set to an idle (high) state. figure 72 illustrates the possible combinations of the frame formats. bits inside brackets are optional. figure 72. frame formats st start bit, always low. (n) data bits (0 to 8). p parity bit. can be odd or even. rxd / txd xck rxd / txd xck ucpol = 0 ucpol = 1 sample sample 1 0 2 3 4 [5] [6] [7] [8] [p] st sp1 [sp2] (st / idle) (idle) frame
150 atmega8535(l) 2502k?avr?10/06 sp stop bit, always high. idle no transfers on the communication line (rxd or txd). an idle line must be high. the frame format used by th e usart is set by the ucsz2: 0, upm1:0 and usbs bits in ucsrb and ucsrc. the receiver and transmitter use the same setting. note that changing the setting of any of these bits will corrupt all ongoing communica tion for both the receiver and transmitter. the usart character size (ucsz2:0) bits select the number of data bits in the frame. the usart parity mode (upm1:0) bits enable and set the type of parity bit. the selec- tion between one or two stop bits is done by the usart stop bit select (usbs) bit. the receiver ignores the second stop bit. an fe (frame error) will therefore only be detected in the cases where the first stop bit is zero. parity bit calculation the parity bit is calculated by doing an exclus ive-or of all the data bits. if odd parity is used, the result of the exclusive or is inverted. the relation between the parity bit and data bits is as follows:: p even parity bit using even parity p odd parity bit using odd parity d n data bit n of the character if used, the parity bit is located between the last data bit and first stop bit of a serial frame. usart initialization the usart has to be initialized before any communication can take place. the initial- ization process normally consists of setting the baud rate, setting frame format and enabling the transmitter or the receiver depending on the usage. for interrupt driven usart operation, the global interrupt flag should be cleared (and interrupts globally disabled) when doing the initialization. before doing a re-initialization with a changed baud rate or frame format, be sure that there are no ongoing transmissions during th e period the registers are changed. the txc flag can be used to check that the transmitter has completed all transfers and the rxc flag can be used to check that there are no unread data in the receive buffer. note that the txc flag must be cleared before each transmission (before udr is written) if it is used for this purpose. p even d n 1 ? d 3 d 2 d 1 d 0 0 p odd d n 1 ? d 3 d 2 d 1 d 0 1 = =
151 atmega8535(l) 2502k?avr?10/06 the following simple usart initialization code examples show one assembly and one c function that are equal in functionality. the examples assume asynchronous opera- tion using polling (no interrupts enabled) and a fixed frame format. the baud rate is given as a function parameter. for the assembly code, the baud rate parameter is assumed to be stored in the r17:r16 registers. when the function writes to the ucsrc register, the ursel bit (msb) must be set due to the sharing of i/o location by ubrrh and ucsrc. note: 1. see ?about code examples? on page 7. more advanced initialization routines can be made that include frame format as parame- ters, disable interrupts and so on. however, many applications use a fixed setting of the baud and control registers, and for these types of applications the initialization code can be placed directly in the main routine or be combined with initialization code for other i/o modules. assembly code example (1) usart_init: ; set baud rate out ubrrh, r17 out ubrrl, r16 ; enable receiver and transmitter ldi r16, (1<>8); ubrrl = ( unsigned char )baud; /* enable receiver and transmitter */ ucsrb = (1< 152 atmega8535(l) 2502k?avr?10/06 data transmission ? the usart transmitter the usart transmitter is enabled by setting the transmit enable (txen) bit in the ucsrb register. when the transmitter is enabled, the normal port operation of the txd pin is overridden by the usart and given the function as the transmitter?s serial output. the baud rate, mode of operation and frame format must be set up once before doing any transmissions. if sy nchronous operation is used, the clock on the xck pin will be overridden and used as transmission clock. sending frames with 5 to 8 data bits a data transmission is initiated by loading the transmit buffer with the data to be trans- mitted. the cpu can load the transmit buffer by writing to the udr i/o location. the buffered data in the transmit buffer will be moved to the shift register when the shift register is ready to send a new frame. the shift register is loaded with new data if it is in idle state (no ongoing transmission) or immediately after the last stop bit of the previ- ous frame is transmitted. when the shift register is loaded with new data, it will transfer one complete frame at the rate given by the baud register, u2x bit or by xck depending on mode of operation. the following code examples show a simple usart transmit func tion based on polling of the data register empty (udre) flag. when using frames with less than eight bits, the most significant bits written to the udr are ignored. the usart has to be initialized before the function can be used. for the assembly code, the data to be sent is assumed to be stored in register r16. note: 1. see ?about code examples? on page 7. the function simply waits for the transmi t buffer to be empty by checking the udre flag, before loading it with new data to be transmitted. if the data register empty inter- rupt is utilized, the inte rrupt routine writes the data into the buffer. assembly code example (1) usart_transmit: ; wait for empty transmit buffer sbis ucsra,udre rjmp usart_transmit ; put data (r16) into buffer, sends the data out udr,r16 ret c code example (1) void usart_transmit( unsigned char data ) { /* wait for empty transmit buffer */ while ( !( ucsra & (1< 153 atmega8535(l) 2502k?avr?10/06 sending frames with 9 data bits if 9-bit characters are used (ucsz = 7), the ni nth bit must be written to the txb8 bit in ucsrb before the low byte of the characte r is written to udr. the following code examples show a transmit fu nction that handles 9-bit characters. for the assembly code, the data to be sent is assumed to be stored in registers r17:r16. note: 1. these transmit functions are written to be general functions. they can be optimized if the contents of the ucsrb is static. (for example, only the txb8 bit of the ucsrb register is used after initialization.) the ninth bit can be used for indicating an address frame when using multi processor communication mode or for other protocol handling as for example synchronization. transmitter flags and interrupts the usart transmitter has two flags that indicate its state: usart data register empty (udre) and transmit complete (txc). both flags can be used for generating interrupts. the data register empty (udre) flag indica tes whether the transmit buffer is ready to receive new data. this bit is set when the transmit buffer is empty, and cleared when the transmit buffer contains data to be transmitted that has not yet been moved into the shift register. for compatibility with fu ture devices, always write this bit to zero when writing the ucsra register. when the data register empty interrupt enable (udrie) bit in ucsrb is written to one, the usart data register empty interrupt will be executed as long as udre is set (pro- vided that global interrupt s are enabled). udre is cleared by writing udr. when assembly code example (1) usart_transmit: ; wait for empty transmit buffer sbis ucsra,udre rjmp usart_transmit ; copy 9th bit from r17 to txb8 cbi ucsrb,txb8 sbrc r17,0 sbi ucsrb,txb8 ; put lsb data (r16) into buffer, sends the data out udr,r16 ret c code example (1) void usart_transmit( unsigned int data ) { /* wait for empty transmit buffer */ while ( !( ucsra & (1< 154 atmega8535(l) 2502k?avr?10/06 interrupt-driven data transmission is used, the data register empty interrupt routine must either write new data to udr in order to clear udre or disable the data register empty interrupt, otherwise a new interrupt will occur once the interrupt routine terminates. the transmit complete (txc) flag bit is set to one when the entire frame in the transmit shift register has been shifted out and there are no new data currently present in the transmit buffer. the txc flag bit is autom atically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location. the txc flag is useful in half-duplex communication interfaces (like the rs-485 standard), where a transmitting application must enter receive mode and free the communication bus immediately after completing the transmission. when the transmit compete interrupt enable (txcie) bit in ucsrb is set, the usart transmit complete interrup t will be executed when the txc flag beco mes set (pro- vided that global interrupts are enabled). when the transmit complete interrupt is used, the interrupt handling routine does not have to clear the txc flag, this is done automat- ically when the interrupt is executed. parity generator the parity generator calculates the parity bit for the serial frame data. when parity bit is enabled (upm1 = 1), the transmitter control logic inserts the parity bit between the last data bit and the first stop bit of the frame that is sent. disabling the transmitter the disabling of the transmitter (setting the txen to zero) will not become effective until ongoing and pending transmissions are completed (i.e., when the transmit shift register and transmit buffer register do not contain data to be transmitted). when dis- abled, the transmitter will no longer override the txd pin.
155 atmega8535(l) 2502k?avr?10/06 data reception ? the usart receiver the usart receiver is enabled by writing the receive enable (rxen) bit in the ucsrb register to one. when the receiver is enabled, the normal pin operation of the rxd pin is overridden by the usart and given the function as the receiver?s serial input. the baud rate, mode of operation and frame format must be set up once before any serial reception can be done. if synchronous operation is used, the clock on the xck pin will be used as a transfer clock. receiving frames with 5 to 8 data bits the receiver starts data reception when it detects a valid start bit. each bit that follows the start bit will be sampled at the baud rate or xck clock, and shifted into the receive shift register until the first stop bit of a frame is received. a second stop bit will be ignored by the receiver. when the first stop bit is received, (i.e., a complete serial frame is present in the receive shift register, th e contents of the shift register will be moved into the receive buffer. the receive buffer can then be read by reading the udr i/o location. the following code example shows a simple usart receive function based on polling of the receive complete (rxc) flag. when us ing frames with less than eight bits the most significant bits of the data read fr om the udr will be masked to zero. the usart has to be initialized before the function can be used. note: 1. see ?about code examples? on page 7. the function simply waits for data to be pres ent in the receive buffer by checking the rxc flag, before reading the buffer and returning the value. assembly code example (1) usart_receive: ; wait for data to be received sbis ucsra, rxc rjmp usart_receive ; get and return received data from buffer in r16, udr ret c code example (1) unsigned char usart_receive( void ) { /* wait for data to be received */ while ( !(ucsra & (1< 156 atmega8535(l) 2502k?avr?10/06 receiving frames with 9 data bits if 9-bit characters are used (ucsz=7) the ninth bit must be read from the rxb8 bit in ucsrb before reading the low bits from the udr. this rule applies to the fe, dor, and pe status flags as well. read status from ucsra, then data from udr. reading the udr i/o location will change the state of the receive bu ffer fifo an d consequently the txb8, fe, dor, and pe bits, which all are stored in the fifo, will change. the following code example shows a simple u sart receive function that handles both 9-bit characters and the status bits. assembly code example (1) usart_receive: ; wait for data to be received sbis ucsra, rxc rjmp usart_receive ; get status and 9th bit, then data from buffer in r18, ucsra in r17, ucsrb in r16, udr ; if error, return -1 andi r18,(1<> 1) & 0x01; return ((resh << 8) | resl); }
157 atmega8535(l) 2502k?avr?10/06 note: 1. see ?about code examples? on page 7. the receive function example reads all the i/o registers into the register file before any computation is done. this gives an opti mal receive buffer utilization since the buffer location read will be free to accept new data as early as possible. receive compete flag and interrupt the usart receiver has one flag that indicates the receiver state. the receive complete (rxc) flag indicates if there are unread data present in the receive buffer. this flag is one when unread data exist in the receive buffer and zero when the receive buffer is empty (i.e., does not contain any unread data). if the receiver is disabled (rxen = 0), the receive buffer will be flushed and cons equently the rxc bit will become zero. when the receive complete interrupt enabl e (rxcie) in ucsrb is set, the usart receive complete interrupt will be executed as long as the rxc flag is set (provided that global interrupts are enabled). when interrupt-driven data reception is used, the receive complete routine must read the received data from udr in order to clear the rxc flag, otherwise a new in terrupt will occur once the in terrupt routine terminates. receiver error flags the usart receiver has three error flags: frame error (fe), data overrun (dor) and parity error (pe). all can be accessed by reading ucsra. common for the error flags is that they are located in the receive buffer together with the frame for which they indicate the error status. due to the buffering of the error flags, the ucsra must be read before the receive bu ffer (udr), since reading the udr i/o location changes the buffer read location. another equality for the error flags is that they can not be altered by software doing a write to the flag location. however, all flags must be set to zero when the ucsra is written for upward compatibilit y of future usart implementations. none of the error flags can generate interrupts. the frame error (fe) flag indicates the state of the first stop bit of the next readable frame stored in the receive buffer. the fe flag is zero when the stop bit was correctly read (as one), and the fe flag will be one when the stop bit was incorrect (zero). this flag can be used for detecting out-of-sync c onditions, detecting break conditions and protocol handling. the fe flag is not affected by the setting of the usbs bit in ucsrc since the receiver ignores all, except for th e first, stop bits. fo r compatibility with future devices, always set this bit to zero when writing to ucsra. the data overrun (dor) flag indicates data loss due to a receiver buffer full condi- tion. a data overrun occurs when the receive buffer is full (two char acters), it is a new character waiting in the receive shift regist er, and a new start bit is detected. if the dor flag is set there was one or more serial frame lost between the frame last read from udr, and the next frame read from udr. for compatibility with future devices, always write this bit to zero when writing to ucsra. the dor flag is cleared when the frame received was successfully moved from the shift register to the receive buffer. the parity error (pe) flag indicates that the next frame in the receive buffer had a parity error when received. if parity check is not enabled the pe bit will always be read zero. for compatibility with future devices, always se t this bit to zero when writing to ucsra. for more details see ?parity bit calculation? on page 150 and ?parity checker? on page 157. parity checker the parity checker is active when the high usart parity mode (upm1) bit is set. the type of parity check to be performed (odd or even) is selected by the upm0 bit. when enabled, the parity checker calculates the par ity of the data bits in incoming frames and compares the result with the parity bit from the serial frame. the result of the check is
158 atmega8535(l) 2502k?avr?10/06 stored in the receive buffer together with the received data and stop bits. the parity error (pe) flag can then be read by software to check if the frame had a parity error. the pe bit is set if the next character that can be read from the receive buffer had a par- ity error when received and the parity checking was enabled at that point (upm1 = 1). this bit is valid until the receive buffer (udr) is read. disabling the receiver in contrast to the transmitter, disabling of the receiver will be immediate. data from ongoing receptions will therefore be lost. wh en disabled (i.e., the rxen is set to zero) the receiver will no longer over ride the normal function of th e rxd port pin. the receiver buffer fifo will be flushed wh en the receiver is disabled. remaining data in the buffer will be lost flushing the receive buffer the receiver buffer fifo will be flushed when the receiver is disabled, i.e., the buffer will be emptied of its contents. unread data will be lost. if the buffer has to be flushed during normal operation, due to for instance an error condition, read the udr i/o loca- tion until the rxc flag is cleared. the following code example shows how to flush the receive buffer. note: 1. see ?about code examples? on page 7. asynchronous data reception the usart includes a clock recovery and a data recovery unit for handling asynchro- nous data reception. the clock recovery logi c is used for synchronizing the internally generated baud rate clock to the incoming asynchronous serial frames at the rxd pin. the data recovery logic samples and low pass filters each incoming bit, thereby improv- ing the noise immunity of the receiver. the asynchronous reception operational range depends on the accuracy of the internal baud rate clock, the rate of the incoming frames, and the frame size in number of bits. asynchronous clock recovery the clock recovery logic synchronizes intern al clock to the incomi ng serial frames. fig- ure 73 illustrates the sampling pr ocess of the start bit of an incoming frame. the sample rate is 16 times the baud rate for normal mode, and eight times the baud rate for double speed mode. the horizon tal arrows illust rate the synchronizatio n variation due to the sampling process. note the larger time variation when using the double speed mode (u2x = 1) of operation. samples denoted zero are samples done when the rxd line is idle (i.e., no comm unication activity). assembly code example (1) usart_flush: sbis ucsra, rxc ret in r16, udr rjmp usart_flush c code example (1) void usart_flush( void ) { unsigned char dummy; while ( ucsra & (1< 159 atmega8535(l) 2502k?avr?10/06 figure 73. start bit sampling when the clock recovery logic detects a high (idle) to low (start) transition on the rxd line, the start bit detection sequence is initiated. let sample 1 denote the first zero-sam- ple as shown in the figure. the clock recovery logic then uses samples 8, 9, and 10 for normal mode, and samples 4, 5, and 6 for double speed mode (indicated with sample numbers inside boxes on the figure), to decide if a valid start bit is received. if two or more of these three samples have logical high levels (the majority wins), the start bit is rejected as a noise spike and the receiver starts looking for the next high to low-transi- tion. if however, a valid start bit is detected, the clock recovery logic is synchronized and the data recovery can begin. the synchronization process is repeated for each start bit. asynchronous data recovery when the receiver clock is synchronized to the start bit, the data recovery can begin. the data recovery unit uses a state machine that has 16 states for each bit in normal mode and eight states for each bit in double speed mode. figure 74 shows the sam- pling of the data bits and the parity bit. each of the samples is given a number that is equal to the state of the recovery unit. figure 74. sampling of data and parity bit the decision of the logic level of the received bit is taken by doing a majority voting of the logic value to the three samples in the center of the received bit. the center samples are emphasized on the figure by having the sample number inside boxes. the majority voting process is done as follows: if two or all three samples have high levels, the received bit is registered to be a logic 1. if two or all three samples have low levels, the received bit is registered to be a logic 0. this majority voting process acts as a low pass filter for the incoming signal on the rxd pin. the recovery process is then repeated until a complete frame is received. including the first stop bit. note that the receiver only uses the first stop bit of a frame. figure 75 shows the sampling of the stop bit and the earliest possible beginning of the start bit of the next frame. 1234567 8 9 10 11 12 13 14 15 16 12 start idle 0 0 bit 0 3 123 4 5 678 12 0 rxd sample (u2x = 0) sample (u2x = 1) 1234567 8 9 10 11 12 13 14 15 16 1 bit n 123 4 5 678 1 rxd sample (u2x = 0) sample (u2x = 1)
160 atmega8535(l) 2502k?avr?10/06 figure 75. stop bit sampling and ne xt start bit sampling the same majority voting is done to the stop bit as done for the other bits in the frame. if the stop bit is registered to have a logic 0 value, the fram e error (fe) fl ag will be set. a new high to low transition indicating the start bit of a new frame can come right after the last of the bits used for majority voting. for normal speed mode, the first low level sample can be at point marked (a) in figur e 75. for double speed mode the first low level must be delayed to (b). (c) marks a stop bit of full length. the early start bit detec- tion influences the operational range of the receiver. asynchronous operational range the operational range of the receiver is dependent on the mismatch between the received bit rate and the internally generated baud rate. if the transmitter is sending frames at too fast or too slow bit rates, or the internally generated baud rate of the receiver does not have a similar (see tabl e 62) base frequency, the receiver will not be able to synchronize the frames to the start bit. the following equations can be used to calculate the ratio of the incoming data rate and internal receiver baud rate. d sum of character size and parity size (d = 5 to 10 bit). s samples per bit. s = 16 for normal speed mode and s = 8 for double speed mode. s f first sample number used for majority voting. s f = 8 for normal speed and s f = 4 for double speed mode. s m middle sample number used for majority voting. s m = 9 for normal speed and s m = 5 for double speed mode. r slow is the ratio of the slowest incoming data rate that can be accepted in relation to the receiver baud rate. r fast is the ratio of the fastest incoming data rate that can be accepted in relation to the receiver baud rate. table 62 and table 63 list the maximum receiver baud rate error that can be tolerated. note that normal speed mode has higher toleration of baud rate variations. 1234567 8 9 10 0/1 0/1 0/1 stop 1 123 4 5 6 0/1 rxd sample (u2x = 0) sample (u2x = 1) (a) (b) (c) r slow d 1 + () s s 1 ? ds ? s f ++ ------------------------------------------ - = r fast d 2 + () s d 1 + () ss m + ----------------------------------- =
161 atmega8535(l) 2502k?avr?10/06 the recommendations of the maximum receiver baud rate error was made under the assumption that the receiver and transmitter equally divides the maximum total error. there are two possible sources for the receivers baud rate error. the receiver?s system clock (xtal) will always have some minor in stability over the supp ly voltage range and the temperature range. when using a crystal to generate the system clock, this is rarely a problem, but for a resonator the system clock may differ more than 2% depending of the resonators tolerance. the second source for the error is more controllable. the baud rate generator can not always do an exact division of the system frequency to get the baud rate wanted. in this case an ubrr value that gives an acceptable low error can be used if possible. table 62. recommended maximum receiver baud rate error for normal speed mode (u2x = 0) d # (data+parity bit) r slow (%) r fast (%) max total error (%) recommended max receiver error (%) 5 93.20 106.67 +6.67/-6.8 3.0 6 94.12 105.79 +5.79/-5.88 2.5 7 94.81 105.11 +5.11 -5.19 2.0 8 95.36 104.58 +4.58/-4.54 2.0 9 95.81 104.14 +4.14/-4.19 1.5 10 96.17 103.78 +3.78/-3.83 1.5 table 63. recommended maximum receiver baud rate error for double speed mode (u2x = 1) d # (data+parity bit) r slow (%) r fast (%) max total error (%) recommended max receiver error (%) 5 94.12 105.66 +5.66/-5.88 2.5 6 94.92 104.92 +4.92/-5.08 2.0 7 95.52 104.35 +4.35/-4.48 1.5 8 96.00 103.90 +3.90/-4.00 1.5 9 96.39 103.53 +3.53/-3.61 1.5 10 96.70 103.23 +3.23/-3.30 1.0
162 atmega8535(l) 2502k?avr?10/06 multi-processor communication mode setting the multi-processor communication mode (mpcm) bit in ucsra enables a fil- tering function of incoming frames received by the usart receiver. frames that do not contain address information will be ignored and not put into the receive buffer. this effectively reduces the number of incomi ng frames that has to be handled by the cpu, in a system with multiple mcus that comm unicate via the same serial bus. the trans- mitter is unaffected by the mpcm setting, but has to be used differently when it is a part of a system utilizing the multi- processor communication mode. if the receiver is set up to receive frames that contain five to eight data bits, then the first stop bit indicates if the frame contains da ta or address information. if the receiver is set up for frames with nine data bits, then the ninth bit (rxb8) is used for identifying address and data frames. when the frame type bit (the first stop or the ninth bit) is one, the frame contains an address. when the frame type bit is zero the frame is a data frame. the multi-processor communication mode enables several slave mcus to receive data from a master mcu. this is done by first decoding an address frame to find out which mcu has been addressed. if a particular slave mcu has been addressed, it will receive the following data frames as normal, while the other slave mc us will ignore the received frames until another address frame is received. using mpcm for an mcu to act as a master mcu, it can use a 9-bit character frame format (ucsz = 7). the ninth bit (txb8) must be set when an address frame (txb8 = 1) or cleared when a data frame (txb = 0) is being transmitted. the slave mcus must, in this case, be set to use a 9-bit character frame format. the following procedure should be used to exchange data in multi-processor communi- cation mode: 1. all slave mcus are in multi-processo r communication mode (mpcm in ucsra is set). 2. the master mcu sends an address frame, and all slaves receive and read this frame. in the slave mcus, the rxc flag in ucsra will be set as normal. 3. each slave mcu reads the udr register and determines if it has been selected. if so, it clears the mpcm bit in ucsra, otherwise it waits for the next address byte and keeps the mpcm setting. 4. the addressed mcu will receive all data frames until a new address frame is received. the other slave mcus, which still have the mpcm bit set, will ignore the data frames. 5. when the last data frame is received by the addressed mcu, the addressed mcu sets the mpcm bit and waits for a new address frame from master. the process then repeats from 2. using any of the 5- to 8-bit character frame formats is possible, but impractical since the receiver must change between using n and n+1 character frame formats. this makes full-duplex operation difficult since the transmitter and receiver uses the same charac- ter size setting. if 5- to 8-bit character frames are used, the transmitter must be set to use two stop bit (usbs = 1) since the first stop bit is used for indicating the frame type. do not use read-modify-write instructions (s bi and cbi) to set or clear the mpcm bit. the mpcm bit shares the same i/o location as the txc flag and this might accidentally be cleared when using sbi or cbi instructions.
163 atmega8535(l) 2502k?avr?10/06 accessing ubrrh/ucsrc registers the ubrrh register shares the same i/o location as the ucsrc register. therefore some special consideration must be taken when accessing this i/o location. write access when doing a write access of this i/o location, the high bit of the value written, the usart register select (ursel) bit, controls which one of the two registers that will be written. if ursel is zero during a writ e operation, the ubrrh value will be updated. if ursel is one, the ucsrc setting will be updated. the following code examples show how to access the two registers. note: 1. see ?about code examples? on page 7. as the code examples illustrate, write accesse s of the two registers are relatively unaf- fected of the sharing of i/o location. assembly code examples (1) ... ; set ubrrh to 2 ldi r16,0x02 out ubrrh,r16 ... ; set the usbs and the ucsz1 bit to one, and ; t he remaining bits to zero. ldi r16,(1< 164 atmega8535(l) 2502k?avr?10/06 read access doing a read access to the ubrrh or the ucsrc register is a more complex opera- tion. however, in most applications, it is rarely necessary to read any of these registers. the read access is controlled by a timed sequence. reading the i/o location once returns the ubrrh register cont ents. if the register locati on was read in previous sys- tem clock cycle, reading the register in t he current clock cycle will return the ucsrc contents. note that the timed sequence fo r reading the ucsrc is an atomic operation. interrupts must therefore be controlled (e.g., by disabling interrupts globally) during the read operation. the following code example shows how to read the ucsrc register contents. note: 1. see ?about code examples? on page 7. the assembly code example returns the ucsrc value in r16. reading the ubrrh contents is not an atomic operation and therefore it can be read as an ordinary register, as long as the previ ous instruction did not access the register location. usart register description usart i/o data register ? udr the usart transmit data buffer register and usart receive data buffer registers share the same i/o address re ferred to as usart data re gister or udr. the transmit data buffer register (txb) will be the de stination for data wri tten to the udr register location. reading the udr regi ster location will return the contents of the receive data buffer register (rxb). assembly code example (1) usart_readucsrc: ; read ucsrc in r16,ubrrh in r16,ucsrc ret c code example (1) unsigned char usart_readucsrc( void ) { unsigned char ucsrc; /* read ucsrc */ ucsrc = ubrrh; ucsrc = ucsrc; return ucsrc; } bit 76543210 rxb[7:0] udr (read) txb[7:0] udr (write) read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
165 atmega8535(l) 2502k?avr?10/06 for 5-, 6-, or 7-bit characters the upper unus ed bits will be ignored by the transmitter and set to zero by the receiver. the transmit buffer can only be written w hen the udre flag in t he ucsra register is set. data written to udr when the udre flag is not set, will be ignored by the usart transmitter. when data is written to the transmit buffer, and the transmitter is enabled, the transmitter will load the data into the transmit shift register when the shift register is empty. then the data will be se rially transmitted on the txd pin. the receive buffer co nsists of a two-level fifo. the fifo will change it s state whenever the receive buffer is accessed. due to this behavior of the receive buffer, do not use read-modify-write instructions (sbi and cbi) on this location. be careful when using bit test instructions (sbic and sbis), since these also will ch ange the state of the fifo. usart control and status register a ? ucsra ? bit 7 ? rxc: usart receive complete this flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (i.e., does not contain any unread data). if the receiver is dis- abled, the receive buffer will be flushed and consequently th e rxc bit will become zero. the rxc flag can be used to generate a receive complete interrupt (see description of the rxcie bit). ? bit 6 ? txc: usart transmit complete this flag bit is set when the entire frame in the transmit shift register has been shifted out and there are no new data currently present in the transmit buffer (udr). the txc flag bit is automatically cleared when a transmi t complete interrupt is executed, or it can be cleared by writing a one to its bit location. the txc flag can generate a transmit complete interrupt (see description of the txcie bit). ? bit 5 ? udre: usart data register empty the udre flag indicates if the transmit buff er (udr) is ready to receive new data. if udre is one, the buffer is empty, and therefore ready to be written. the udre flag can generate a data register empty interrupt (see description of the udrie bit). udre is set after a reset to indicate that the transmitter is ready. ? bit 4 ? fe: frame error this bit is set if the next character in the receive buffer had a frame error when received. for example, when the first stop bit of the next character in the receive buffer is zero. this bit is valid until the receive bu ffer (udr) is read. th e fe bit is zero when the stop bit of received data is one. always se t this bit to zero when writing to ucsra. ? bit 3 ? dor: data overrun this bit is set if a data overrun condition is detected. a data overrun occurs when the receive buffer is full (two characters), it is a new character waiting in the receive shift register, and a new start bit is detected. this bit is valid until the receive buffer (udr) is read. always set this bit to zero when writing to ucsra. ? bit 2 ? pe: parity error this bit is set if the next character in the receive buffer had a parity error when received and the parity checking was enabled at that point (upm1 = 1). this bit is valid until the receive buffer (udr) is read. always set this bit to zero when writing to ucsra. bit 76543210 rxc txc udre fe dor pe u2x mpcm ucsra read/write r r/w r r r r r/w r/w initial value00100000
166 atmega8535(l) 2502k?avr?10/06 ? bit 1 ? u2x: double the usart transmission speed this bit only has effect for the asynchronous operation. write this bit to zero when using synchronous operation. writing this bit to one will reduce the divisor of the baud rate divider from 16 to 8 effec- tively doubling the transfer rate for asynchronous communication. ? bit 0 ? mpcm: multi-processor communication mode this bit enables the multi-processor communication mode. when the mpcm bit is writ- ten to one, all the incoming frames received by the usart receiver that do not contain address information will be igno red. the transmitter is una ffected by the mpcm setting. for more detailed information see ?multi-processor communication mode? on page 162. usart control and status register b ? ucsrb ? bit 7 ? rxcie: rx complete interrupt enable writing this bit to one enables interrupt on the rxc flag. a usart receive complete interrupt will be generat ed only if the rxcie bit is writ ten to one, t he global interrupt flag in sreg is written to one and the rxc bit in ucsra is set. ? bit 6 ? txcie: tx complete interrupt enable writing this bit to one enables interrupt on the txc flag. a usart transmit complete interrupt will be generated only if the txcie bi t is written to one, the global interrupt flag in sreg is written to one and the txc bit in ucsra is set. ? bit 5 ? udrie: usart data register empty interrupt enable writing this bit to one enab les interrupt on the udre flag. a data register empty inter- rupt will be generated only if the udrie bit is written to one, the global interrupt flag in sreg is written to one and the udre bit in ucsra is set. ? bit 4 ? rxen: receiver enable writing this bit to one enables the usart receiver. the receiver will override normal port operation for the rxd pin when enabled. disabling the receiver will flush the receive buffer invalidating the fe, dor, and pe flags. ? bit 3 ? txen: transmitter enable writing this bit to one enables the usart transmitter. the trans mitter will override nor- mal port operation for the txd pin when enabled. the disabling of the transmitter (writing txen to zero) will not become effe ctive until ongoing and pending transmis- sions are completed, (i.e., when the transmit shift register and transmit buffer register do not contain data to be transmitted). when disabled, the transmitter will no longer override the txd port. ? bit 2 ? ucsz2: character size the ucsz2 bits combined with the ucsz1:0 bi t in ucsrc sets the number of data bits (character size) in a frame the receiver and transmitter use. ? bit 1 ? rxb8: receive data bit 8 rxb8 is the ninth data bit of the received character when operating with serial frames with nine data bits. must be read before reading the low bits from udr. ? bit 0 ? txb8: transmit data bit 8 bit 76543210 rxcie txcie udrie rxen txen ucsz2 rxb8 txb8 ucsrb read/write r/w r/w r/w r/w r/w r/w r r/w initial value00000000
167 atmega8535(l) 2502k?avr?10/06 txb8 is the ninth data bit in the character to be transmitted when operating with serial frames with nine data bits. must be written before writing the low bits to udr. usart control and status register c ? ucsrc (1) note: 1. the ucsrc register shares the same i/o location as the ubrrh register. see the ?accessing ubrrh/ucsrc registers? on pa ge 163 section which describes how to access this register. ? bit 7 ? ursel: register select this bit selects between accessing the ucsr c or the ubrrh register. it is read as one when reading ucsrc. the ursel must be one when writing the ucsrc. ? bit 6 ? umsel: usart mode select this bit selects between asynchronous and synchronous mode of operation. bit 76543210 ursel umsel upm1 upm0 usbs ucsz1 ucsz0 ucpol ucsrc read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value10000110 table 64. umsel bit settings umsel mode 0 asynchronous operation 1 synchronous operation
168 atmega8535(l) 2502k?avr?10/06 ? bit 5:4 ? upm1:0: parity mode these bits enable and set type of parity generation and check. if enabled, the transmit- ter will automatically generate and send th e parity of the transmitted data bits within each frame. the receiver will generate a parity value for the incoming data and com- pare it to the upm0 setting. if a mismatch is detected, th e pe flag in ucsra will be set. ? bit 3 ? usbs: stop bit select this bit selects the number of stop bits to be inserted by the transmitter. the receiver ignores this setting. ? bit 2:1 ? ucsz1:0: character size the ucsz1:0 bits combined with the ucsz2 bit in ucsrb sets the number of data bits (character size) in a frame the receiver and transmitter use. ? bit 0 ? ucpol: clock polarity table 65. upm bits settings upm1 upm0 parity mode 0 0 disabled 01reserved 1 0 enabled, even parity 1 1 enabled, odd parity table 66. usbs bit settings usbs stop bit(s) 01-bit 12-bit table 67. ucsz bits settings ucsz2 ucsz1 ucsz0 character size 0005-bit 0016-bit 0107-bit 0118-bit 100reserved 101reserved 110reserved 1119-bit
169 atmega8535(l) 2502k?avr?10/06 this bit is used for synchronous mode only. write this bit to zero when asynchronous mode is used. the ucpol bit sets th e relationship between data output change and data input sample, and th e synchronous clock (xck). usart baud rate registers ? ubrrl and ubrrh (1) note: 1. the ubrrh register shares the same i/o location as the ucsrc register. see the ?accessing ubrrh/ucsrc registers? on pa ge 163 section which describes how to access this register. ? bit 15 ? ursel: register select this bit selects between accessing the ubrr h or the ucsrc register. it is read as zero when reading ubrrh. the ursel mu st be zero when writing the ubrrh. ? bit 14:12 ? reserved bits these bits are reserved for fu ture use. for compatibility wit h future devices, these bit must be written to zero when ubrrh is written. ? bit 11:0 ? ubrr11:0: usart baud rate register this is a 12-bit register which contains the usart baud rate. the ubrrh contains the four most significant bits, and the ubrrl contai ns the eight least significant bits of the usart baud rate. ongoing transmissions by the transmitter and receiver will be cor- rupted if the baud rate is changed. writing ubrrl will tr igger an imme diate update of the baud rate prescaler. table 68. ucpol bit settings ucpol transmitted data changed (output of txd pin) received data sampled (input on rxd pin) 0 rising xck edge falling xck edge 1 falling xck edge rising xck edge bit 151413121110 9 8 ursel ? ? ? ubrr[11:8] ubrrh ubrr[7:0] ubrrl 76543210 read/write r/w r r r r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 00000000
170 atmega8535(l) 2502k?avr?10/06 examples of baud rate setting for standard crystal and resonator frequencies, the most commonly used baud rates for asynchronous operation can be generated by using the ubrr settings in table 69. ubrr values which yield an actual baud rate differing less than 0.5% from the target baud rate, are bold in the ta ble. higher error ratings are a cceptable, but the receiver will have less noise resistance when the error rati ngs are high, especially for large serial frames (see ?asynchronous operational range? on page 160). the error values are cal- culated using the following equation: error[%] baudrate closest match baudrate -------------------------------------------------------- 1 ? ?? ?? 100% ? = table 69. examples of ubrr settings for co mmonly used oscillator frequencies baud rate (bps) f osc = 1.0000 mhz f osc = 1.8432 mhz f osc = 2.0000 mhz u2x = 0 u2x = 1 u2x = 0 u2x = 1 u2x = 0 u2x = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 250.2%510.2%470.0%950.0%510.2%1030.2% 4800 120.2%250.2%230.0%470.0%250.2%510.2% 9600 6 -7.0% 12 0.2% 11 0.0% 23 0.0% 12 0.2% 25 0.2% 14.4k 3 8.5% 8 -3.5% 7 0.0% 15 0.0% 8 -3.5% 16 2.1% 19.2k 2 8.5% 6 -7.0% 5 0.0% 11 0.0% 6 -7.0% 12 0.2% 28.8k 1 8.5% 3 8.5% 3 0.0% 7 0.0% 3 8.5% 8 -3.5% 38.4k 1 -18.6% 2 8.5% 2 0.0% 5 0.0% 2 8.5% 6 -7.0% 57.6k 0 8.5% 1 8.5% 1 0.0% 3 0.0% 1 8.5% 3 8.5% 76.8k ? ? 1 -18.6% 1 -25.0% 2 0.0% 1 -18.6% 2 8.5% 115.2k ? ? 0 8.5% 0 0.0% 1 0.0% 0 8.5% 1 8.5% 230.4k??????00.0%???? 250k??????????00.0% max (1) 62.5 kbps 125 kbps 115.2 kbps 2 30.4 kbps 125 kbps 250 kbps 1. ubrr = 0, error = 0.0%
171 atmega8535(l) 2502k?avr?10/06 table 70. examples of ubrr settings for commonl y used oscillator frequencies (continued) baud rate (bps) f osc = 3.6864 mhz f osc = 4.0000 mhz f osc = 7.3728 mhz u2x = 0 u2x = 1 u2x = 0 u2x = 1 u2x = 0 u2x = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 95 0.0% 191 0.0% 103 0.2% 207 0.2% 191 0.0% 383 0.0% 4800 47 0.0% 95 0.0% 51 0.2% 103 0.2% 95 0.0% 191 0.0% 9600 230.0%470.0%250.2%510.2%470.0%950.0% 14.4k 15 0.0% 31 0.0% 16 2.1% 34 -0.8% 31 0.0% 63 0.0% 19.2k 11 0.0% 23 0.0% 12 0.2% 25 0.2% 23 0.0% 47 0.0% 28.8k 7 0.0% 15 0.0% 8 -3.5% 16 2.1% 15 0.0% 31 0.0% 38.4k 5 0.0% 11 0.0% 6 -7.0% 12 0.2% 11 0.0% 23 0.0% 57.6k 3 0.0% 7 0.0% 3 8.5% 8 -3.5% 7 0.0% 15 0.0% 76.8k 2 0.0% 5 0.0% 2 8.5% 6 -7.0% 5 0.0% 11 0.0% 115.2k 1 0.0% 3 0.0% 1 8.5% 3 8.5% 3 0.0% 7 0.0% 230.4k 0 0.0% 1 0.0% 0 8.5% 1 8.5% 1 0.0% 3 0.0% 250k 0 -7.8% 1 -7.8% 0 0.0% 1 0.0% 1 -7.8% 3 -7.8% 0.5m ? ? 0 -7.8% ? ? 0 0.0% 0 -7.8% 1 -7.8% 1m ??????????0-7.8% max (1) 230.4 kbps 460.8 kbps 250k bps 0.5 mbps 460.8 kbps 921.6 kbps 1. ubrr = 0, error = 0.0%
172 atmega8535(l) 2502k?avr?10/06 table 71. examples of ubrr settings for commonl y used oscillator frequencies (continued) baud rate (bps) f osc = 8.0000 mhz f osc = 11.0592 mhz f osc = 14.7456 mhz u2x = 0 u2x = 1 u2x = 0 u2x = 1 u2x = 0 u2x = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 207 0.2% 416 -0.1% 287 0.0% 575 0.0% 383 0.0% 767 0.0% 4800 103 0.2% 207 0.2% 143 0.0% 287 0.0% 191 0.0% 383 0.0% 9600 51 0.2% 103 0.2% 71 0.0% 143 0.0% 95 0.0% 191 0.0% 14.4k 34 -0.8% 68 0.6% 47 0.0% 95 0.0% 63 0.0% 127 0.0% 19.2k 25 0.2% 51 0.2% 35 0.0% 71 0.0% 47 0.0% 95 0.0% 28.8k 16 2.1% 34 -0.8% 23 0.0% 47 0.0% 31 0.0% 63 0.0% 38.4k 12 0.2% 25 0.2% 17 0.0% 35 0.0% 23 0.0% 47 0.0% 57.6k 8 -3.5% 16 2.1% 11 0.0% 23 0.0% 15 0.0% 31 0.0% 76.8k 6 -7.0% 12 0.2% 8 0.0% 17 0.0% 11 0.0% 23 0.0% 115.2k 3 8.5% 8 -3.5% 5 0.0% 11 0.0% 7 0.0% 15 0.0% 230.4k 1 8.5% 3 8.5% 2 0.0% 5 0.0% 3 0.0% 7 0.0% 250k 1 0.0% 3 0.0% 2 -7.8% 5 -7.8% 3 -7.8% 6 5.3% 0.5m 0 0.0% 1 0.0% ? ? 2 -7.8% 1 -7.8% 3 -7.8% 1m ? ? 0 0.0% ? ? ? ? 0 -7.8% 1 -7.8% max (1) 0.5 mbps 1 mbps 691.2 kbps 1.3824 mbps 921.6 kbps 1.8432 mbps 1. ubrr = 0, error = 0.0%
173 atmega8535(l) 2502k?avr?10/06 table 72. examples of ubrr settings for commonl y used oscillator frequencies (continued) baud rate (bps) f osc = 16.0000 mhz f osc = 18.4320 mhz f osc = 20.0000 mhz u2x = 0 u2x = 1 u2x = 0 u2x = 1 u2x = 0 u2x = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 416 -0.1% 832 0.0% 479 0.0% 959 0.0% 520 0.0% 1041 0.0% 4800 207 0.2% 416 -0.1% 239 0.0% 479 0.0% 259 0.2% 520 0.0% 9600 103 0.2% 207 0.2% 119 0.0% 239 0.0% 129 0.2% 259 0.2% 14.4k 68 0.6% 138 -0.1% 79 0.0% 159 0.0% 86 -0.2% 173 -0.2% 19.2k 51 0.2% 103 0.2% 59 0.0% 119 0.0% 64 0.2% 129 0.2% 28.8k 34 -0.8% 68 0.6% 39 0.0% 79 0.0% 42 0.9% 86 -0.2% 38.4k 25 0.2% 51 0.2% 29 0.0% 59 0.0% 32 -1.4% 64 0.2% 57.6k 16 2.1% 34 -0.8% 19 0.0% 39 0.0% 21 -1.4% 42 0.9% 76.8k 12 0.2% 25 0.2% 14 0.0% 29 0.0% 15 1.7% 32 -1.4% 115.2k 8 -3.5% 16 2.1% 9 0.0% 19 0.0% 10 -1.4% 21 -1.4% 230.4k 3 8.5% 8 -3.5% 4 0.0% 9 0.0% 4 8.5% 10 -1.4% 250k 3 0.0% 7 0.0% 4 -7.8% 8 2.4% 4 0.0% 9 0.0% 0.5m 1 0.0% 3 0.0% ? ? 4 -7.8% ? ? 4 0.0% 1m 0 0.0% 1 0.0% ? ? ? ? ? ? ? ? max (1) 1 mbps 2 mbps 1.152 mbps 2.3 04 mbps 1.25 mbps 2.5 mbps 1. ubrr = 0, error = 0.0%
174 atmega8535(l) 2502k?avr?10/06 two-wire serial interface features ? simple yet powerful and flexible communication interface, only two bus lines needed ? both master and slave operation supported ? device can operate as transmitter or receiver ? 7-bit address space allows up to 128 different slave addresses ? multi-master arbitration support ? up to 400 khz data transfer speed ? slew-rate limited output drivers ? noise suppression circuitry rejects spikes on bus lines ? fully programmable slave address with general call support ? address recognition causes wake-up when avr is in sleep mode two-wire serial interface bus definition the two-wire serial interface (twi) is ideally suited for typical microcontroller applica- tions. the twi protocol allows the system s designer to interconnect up to 128 different devices using only two bi-directional bus lines, one for clock (scl) and one for data (sda). the only external hardware needed to implement the bus is a single pull-up resistor for each of the twi bus lines. a ll devices connected to the bus have individual addresses, and mechanisms for resolving bus contention are inherent in the twi protocol. figure 76. twi bus interconnection twi terminology the following definitions are frequently encountered in this section. device 1 device 2 device 3 device n sda scl ........ r1 r2 v cc table 73. twi terminology term description master the device that initiates and terminates a transmission. the master also generates the scl clock. slave the device addressed by a master. transmitter the device placing data on the bus. receiver the device reading data from the bus.
175 atmega8535(l) 2502k?avr?10/06 electrical interconnection as depicted in figure 76, both bus lines are connected to the positive supply voltage through pull-up resistors. the bus drivers of all twi-compliant devices are open-drain or open-collector. this implements a wired-and function which is essential to the opera- tion of the interface. a low level on a twi bus line is generated when one or more twi devices output a zero. a high level is output when all twi devices tri-state their outputs, allowing the pull-up resistors to pull the line high. note that all avr devices connected to the twi bus must be powered in order to allow any bus operation. the number of devices that can be connect ed to the bus is only limited by the bus capacitance limit of 400 pf and the 7-bit sl ave address space. a detailed specification of the electrical characteristics of the twi is given in ?two-wire serial interface character- istics? on page 259. two different sets of specifications are presented there, one relevant for bus speeds below 100 khz, and one valid for bus speeds up to 400 khz. data transfer and frame format transferring bits each data bit transferred on the twi bus is accompanied by a pulse on the clock line. the level of the data line must be stable when the clock line is high. the only exception to this rule is for generating start and stop conditions. figure 77. data validity start and stop conditions the master initiates and terminates a data transmission. the transmission is initiated when the master issues a start condition on the bus, and it is terminated when the master issues a stop condition. between a start and a stop condition, the bus is considered busy, and no other master should tr y to seize control of the bus. a special case occurs when a new start condition is issued between a start and stop con- dition. this is referred to as a repe ated start condition, and is used when the master wishes to initiate a new transfer without relinquishing control of the bus. after a repeated start, the bus is considered busy until the next stop. this is identical to the start behavior, and therefore start is used to describe both start and repeated start for the rema inder of this dat asheet, unless otherwise noted. as depicted below, start and stop conditions are signalled by changing the level of the sda line when the scl line is high. sda scl data stable data stable data change
176 atmega8535(l) 2502k?avr?10/06 figure 78. start, repeated start, and stop conditions address packet format all address packets transmitted on the twi bus are nine bits long, consisting of seven address bits, one read/write control bit and an acknowledge bit. if the read/write bit is set, a read operation is to be performed, otherwise a write operation should be per- formed. when a slave recognizes that it is being addressed, it should acknowledge by pulling sda low in the ninth scl (ack) cycl e. if the addressed slave is busy, or for some other reason can not service the master?s request, the sda line should be left high in the ack clock cycle. the master c an then transmit a st op condition, or a repeated start condition to initiate a ne w transmission. an address packet consist- ing of a slave address and a read or a write bit is called sla+r or sla+w, respectively. the msb of the address byte is transmitted fi rst. slave addresses can freely be allo- cated by the designer, but the address 0000 000 is reserved for a general call. when a general call is issued, all slaves should respond by pulling the sda line low in the ack cycle. a general call is used when a master wishes to transmit the same mes- sage to several slaves in the system. when the general call addres s followed by a write bit is transmitted on the bus, all slaves set up to acknowledge the general call will pull the sda line low in the ack cycle. the followi ng data packets will then be received by all the slaves that acknowledged the general call. note that transmitting the general call address followed by a read bit is meaningless , as this would cause contention if several slaves started transmitting different data. all addresses of the format 1111 xxx should be reserved for future purposes. figure 79. address packet format data packet format all data packets transmitted on the twi bus are nine bits long, consisting of one data byte and an acknowledge bit. during a data transfer, the master generates the clock and the start and stop conditions, while the re ceiver is responsible for acknowledging the reception. an acknowledge (ack) is si gnalled by the receiver pulling the sda line low during the ninth scl cycle. if the receiv er leaves the sda line high, a nack is sig- nalled. when the receiver has received the last byte, or for some reason cannot receive any more bytes, it should inform the transmitter by sending a nack after the final byte. the msb of the data byte is transmitted first. sda scl start stop repeated start stop start sda scl start 12 789 addr msb addr lsb r/w ack
177 atmega8535(l) 2502k?avr?10/06 figure 80. data packet format combining address and data packets into a transmission a transmission basically consists of a star t condition, a sla+r/w, one or more data packets and a stop condition. an empty me ssage, consisting of a start followed by a stop condition is illegal. note that the wired-anding of the scl line can be used to implement handshaking between the master and the slave. the slave can extend the scl low period by pulling the scl line low. this is useful if the clock speed set up by the master is too fast for the slave or the slav e needs extra time for processing between the data transmissions. the slav e extending the scl low period will not affect the scl high period, which is determined by the master. as a consequence, th e slave can reduce the twi data transfer speed by prolonging the scl duty cycle. figure 81 shows a typical data transmission. note that several data bytes can be trans- mitted between the sla+r/w and the stop condition, depending on the software protocol implemented by the application software. figure 81. typical data transmission multi-master bus systems, arbitration and synchronization the twi protocol allows bus systems with several masters. special concerns have been taken in order to ensure that transmissi ons will proceed as normal, even if two or more masters initiate a transm ission at the same time. two problems arise in multi-mas- ter systems: ? an algorithm must be implemented allowing only one of the masters to complete the transmission. all other masters should cease transmission when they discover that they have lost the selection process. this selection process is called arbitration. when a contending master discovers that it has lost the arbitration process, it should immediately switch to slave mode to check whether it is being addressed by the winning master. the fact that multiple masters have started transmission at the same time should not be detectable to the slaves, i.e., the data being transferred on the bus must not be corrupted. ? different masters may use different scl frequencies. a scheme must be devised to synchronize the serial clocks from all masters, in order to let the transmission proceed in a lockstep fashion. this will facilitate the arbitration process. the wired-anding of the bus lines is used to solve both these problems. the serial clocks from all masters will be wired-anded, yielding a combined clock with a high 12 789 data msb data lsb ack aggregate sda sda from transmitter sda from receiver scl from master sla+r/w data byte stop, repeated start or next data byte 12 789 data byte data msb data lsb ack sda scl start 12 789 addr msb addr lsb r/w ack sla+r/w stop
178 atmega8535(l) 2502k?avr?10/06 period equal to the one from the master with the shortest high period. the low period of the combined clock is equal to the low period of the master with the longest low period. note that all masters listen to the scl line, effectively starting to count their scl high and low time-out periods when the combined scl line goes high or low, respectively. figure 82. scl synchronization between multiple masters arbitration is carried out by all masters continuously monitoring the sda line after out- putting data. if the value read from the sda line does not match the value the master had output, it has lost the arbitration. note that a master can only lose arbitration when it outputs a high sda value while another master outputs a low value. the losing master should immediately go to slave mode, checki ng if it is being addressed by the winning master. the sda line should be left high, but losing masters are allowed to generate a clock signal until the end of the current data or address packet. arbitration will continue until only one master remains, and this may take many bits. if several masters are trying to address the same slave, arbitrat ion will continue into the data packet. figure 83. arbitration between two masters ta low ta high scl from master a scl from master b scl bus line tb low tb high masters start counting low period masters start counting high period sda from master a sda from master b sda line synchronized scl line start master a loses arbitration, sda a sda
179 atmega8535(l) 2502k?avr?10/06 note that arbitration is not allowed between: ? a repeated start cond ition and a data bit ? a stop condition and a data bit ? a repeated start and a stop condition it is the user software?s re sponsibility to ensure that th ese illegal arbitration conditions never occur. this implies that in multi-master systems, all data transfers must use the same composition of sla+r/w and data pa ckets. in other words: all transmissions must contain the same number of data packets, otherwise the result of the arbitration is undefined. overview of the twi module the twi module is comprised of several submodules, as shown in figure 84. all regis- ters drawn in a thick line are accessible through the avr data bus. figure 84. overview of the twi module scl and sda pins these pins interface the avr twi with the rest of the mcu system. the output drivers contain a slew-rate limiter in order to conform to the twi specification. the input stages contain a spike suppression unit removing spikes shorter than 50 ns. note that the inter- nal pull-ups in the avr pads can be enabled by setting the port bits corresponding to the scl and sda pins, as explained in the i/o port section. the internal pull-ups can in some systems eliminate the need for external ones. twi unit address register (twar) address match unit address comparator control unit control register (twcr) status register (twsr) state machine and status control scl slew-rate control spike filter sda slew-rate control spike filter bit rate generator bit rate register (twbr) prescaler bus interface unit start / stop control arbitration detection ack spike suppression address/data shift register (twdr)
180 atmega8535(l) 2502k?avr?10/06 bit rate generator unit this unit controls the period of scl when operating in a master mode. the scl period is controlled by settings in the twi bit rate register (twbr) and the prescaler bits in the twi status register (twsr). slave operati on does not depend on bit rate or pres- caler settings, but the cpu clock frequency in the slave must be at least 16 times higher than the scl frequency. note that slaves may prolong the scl low period, thereby reducing the average twi bus clock period. the scl frequency is generated according to the following equation: ? twbr = value of the twi bit rate register ? twps = value of the prescaler bits in the twi status register note: pull-up resistor values should be selected according to the scl frequency and the capacitive bus line load. see table 112 on page 259 for value of pull-up resistor. bus interface unit this unit contains the data and address shift register (twdr), a start/stop con- troller and arbitration detection hardware. the twdr contains the address or data bytes to be transmitted, or the address or data bytes received. in addition to the 8-bit twdr, the bus interface unit also contains a register containing the (n)ack bit to be transmitted or received. this (n)ack register is not directly accessible by the applica- tion software. however, when receiving, it can be set or cleared by manipulating the twi control register (twcr). when in transmitter mode, the value of the received (n)ack bit can be determined by the value in the twsr. the start/stop controller is responsi ble for generation and detection of start, repeated start, and stop conditions. the start/stop controller is able to detect start and stop conditions even when the avr mcu is in one of the sleep modes, enabling the mcu to wake up if addressed by a master. if the twi has initiated a transmission as master, the arbitration detection hardware continuously monitors the transmission trying to determine if arbitration is in process. if the twi has lost an arbitration, the control unit is informed. correct action can then be taken and appropriate status codes generated. address match unit the address match unit checks if received address bytes match the 7-bit address in the twi address register (twar). if the twi general call recognit ion enable (twgce) bit in the twar is written to one, all incoming address bits will also be compared against the general call address. upon an address match, the control unit is informed, allowing correct action to be taken. the tw i may or may not acknowledge its address, depending on settings in the twcr. the address match unit is able to compare addresses even when the avr mcu is in sleep mode, enabling the mcu to wake up if addressed by a master. control unit the control unit monitors the twi bus and generates responses corresponding to set- tings in the twi control register (twcr). when an event requiring the attention of the application occurs on the twi bus, the twi in terrupt flag (twint) is asserted. in the next clock cycle, the twi status register (tws r) is updated with a status code identify- ing the event. the twsr only contains re levant status information when the twi interrupt flag is asserted. at all other times, the twsr contains a special status code indicating that no relevant status information is available. as long as the twint flag is set, the scl line is held low. this allows the application software to complete its tasks before allowing the twi transmission to continue. the twint flag is set in the following situations: scl frequency cpu clock frequency 16 2(twbr) 4 twps ? + ----------------------------------------------------------- =
181 atmega8535(l) 2502k?avr?10/06 ? after the twi has transmitted a start/repeated start condition. ? after the twi has transmitted sla+r/w. ? after the twi has transmitted an address byte. ? after the twi has lost arbitration. ? after the twi has been addressed by own slave address or general call. ? after the twi has received a data byte. ? after a stop or repeated start has been received while still addressed as a slave. ? when a bus error has occurred due to an illegal start or stop condition. twi register description twi bit rate register ? twbr ? bits 7..0 ? twi bit rate register twbr selects the division factor for the bit rate generator. the bit rate generator is a frequency divider which generates the scl clock frequency in the master modes. see ?bit rate generator unit? on page 180 for calculating bit rates. twi control register ? twcr the twcr is used to control the operation of the twi. it is used to enable the twi, to initiate a master access by applying a start condition to the bus, to generate a receiver acknowledge, to generate a stop condition, and to control halting of the bus while the data to be written to the bus are written to the twdr. it also indicates a write collision if data is attempted written to twdr while the register is inaccessible. ? bit 7 ? twint: twi interrupt flag this bit is set by hardware when the twi has finished its current job and expects appli- cation software resp onse. if the i-bit in sreg and twie in twcr are set, the mcu will jump to the twi interrupt vector. while the twint flag is set, the scl low period is stretched. the twint flag must be cleared by software by writing a logic one to it. note that this flag is not automatically cleared by hardware when executing the interrupt rou- tine. also note that clearing this flag starts the operation of the twi, so all accesses to the twi address register (twar), twi stat us register (twsr), and twi data regis- ter (twdr) must be complete before clearing this flag. ? bit 6 ? twea: twi enable acknowledge bit the twea bit controls the generation of the acknowledge pulse. if the twea bit is writ- ten to one, the ack pulse is generated on the twi bus if the following conditions are met: 1. the device?s own slave address has been received. 2. a general call has been received, while the twgce bit in the twar is set. 3. a data byte has been received in master receiver or slave receiver mode. bit 76543210 twbr7 twbr6 twbr5 twbr4 twbr3 twbr2 twbr1 twbr0 twbr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 twint twea twsta twsto twwc twen ? twie twcr read/write r/w r/w r/w r/w r r/w r r/w initial value00000000
182 atmega8535(l) 2502k?avr?10/06 by writing the twea bit to zero, the device can be virtually disconnected from the two- wire serial bus temporarily. address recognition can then be resumed by writing the twea bit to one again. ? bit 5 ? twsta: twi start condition bit the application writes the twsta bit to one when it desires to become a master on the two-wire serial bus. the twi hardware checks if the bus is available, and generates a start condition on the bus if it is free. however, if the bus is not free, the twi waits until a stop condition is detected, and then generates a new start condition to claim the bus master status. twsta must be cleared by software when the start condition has been transmitted. ? bit 4 ? twsto: twi stop condition bit writing the twsto bit to one in master mode will generat e a stop condition on the two-wire serial bus. when the stop condition is executed on the bus, the twsto bit is cleared automatically. in slave mode, setting the twsto bit can be used to recover from an error conditi on. this will not generate a stop condition, but the twi returns to a well-defined unaddressed slave mode and releases the scl and sda lines to a high impedance state. ? bit 3 ? twwc: twi write collision flag the twwc bit is set when attempting to wr ite to the twi data register ? twdr when twint is low. this flag is cleared by writ ing the twdr register when twint is high. ? bit 2 ? twen: twi enable bit the twen bit enables twi operation and ac tivates the twi interface. when twen is written to one, the twi takes control over the i/o pins connected to the scl and sda pins, enabling the slew-rate limiters and spike filters. if this bit is written to zero, the twi is switched off and all twi transmissions are terminated, regardless of any ongoing operation. ? bit 1 ? res: reserved bit this bit is a reserved bit an d will always read as zero. ? bit 0 ? twie: twi interrupt enable when this bit is written to one, and the i-bi t in sreg is set, the twi interrupt request will be activated for as long as the twint flag is high.
183 atmega8535(l) 2502k?avr?10/06 twi status register ? twsr ? bits 7..3 ? tws: twi status these five bits reflect the status of the tw i logic and the two-wire serial bus. the dif- ferent status codes are described later in this section. note that the value read from twsr contains both the 5-bit status value and the 2-bit prescaler value. the application designer should mask the pres caler bits to zero when c hecking the status bits. this makes status checking independent of prescaler setting. this approach is used in this datasheet, unless otherwise noted. ? bit 2 ? res: reserved bit this bit is reserved and will always read as zero. ? bits 1..0 ? twps: twi prescaler bits these bits can be read and written, and control the bit rate prescaler. to calculate bit rates, see ?bit rate generator unit? on page 180. the value of twps1..0 is used in the equation. twi data register ? twdr in transmit mode, twdr contains the next byte to be transmitted. in receive mode, the twdr contains the last byte received. it is writable while the twi is not in the process of shifting a byte. this occurs when the twi interrupt flag (twint) is set by hardware. note that the data register cannot be initialized by the user before the first interrupt occurs. the data in twdr remains stable as long as twint is set. while data is shifted out, data on the bus is simultaneously shifted in. twdr always contains the last byte present on the bus, except after a wake-up from a sleep mode by the twi interrupt. in this case, the contents of twdr is undefined. in the case of a lost bus arbitration, no data is lost in the transition from master to slave. handling of the ack bit is controlled automatically by the twi logic, the cp u cannot access the ack bit directly. ? bits 7..0 ? twd: twi data register these eight bits constitute th e next data byte to be transmitted, or the latest data byte received on the two-wire serial bus. twi (slave) address register ? twar bit 76543210 tws7 tws6 tws5 tws4 tws3 ? twps1 twps0 twsr read/writerrrrrrr/wr/w initial value11111000 table 74. twi bit rate prescaler twps1 twps0 prescaler value 001 014 1016 1164 bit 76543210 twd7 twd6 twd5 twd4 twd3 twd2 twd1 twd0 twdr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value11111111 bit 76543210 twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce twar
184 atmega8535(l) 2502k?avr?10/06 the twar should be loaded with the 7-bit slave address (in the seven most significant bits of twar) to which the twi will respon d when programmed as a slave transmitter or receiver, and not needed in the master modes. in multimaster systems, twar must be set in masters which can be addressed as slaves by other masters. the lsb of twar is used to enable recognition of the general call address (0x00). there is an associated address comparator that looks for the slave address (or general call address if enabled) in the received serial address. if a match is found, an interrupt request is generated. ? bits 7..1 ? twa: twi (slave) address register these seven bits constitute the slave address of the twi unit. ? bit 0 ? twgce: twi general call recognition enable bit if set, this bit enables the recognition of a general call given over the two-wire serial bus. read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value11111110
185 atmega8535(l) 2502k?avr?10/06 using the twi the avr twi is byte-oriented and interrupt based. interrupts are issued after all bus events, like reception of a byte or transmis sion of a start condition. because the twi is interrupt-based, the application software is free to carry on other operations during a twi byte transfer. note that the twi interrupt enable (twie) bit in twcr together with the global interrupt enable bit in sreg a llow the application to decide whether or not assertion of the twint flag should generate an interrupt request. if the twie bit is cleared, the application must poll the twint fl ag in order to detect actions on the twi bus. when the twint flag is asserted, the twi has finished an operation and awaits appli- cation response. in this case, the twi st atus register (twsr) contains a value indicating the current state of the twi bus. the application software can then decide how the twi should behave in the next tw i bus cycle by manipulating the twcr and twdr registers. figure 85 is a simple example of how the ap plication can interface to the twi hardware. in this example, a master wishes to transmit a single data byte to a slave. this descrip- tion is quite abstract, a more detailed explanation follows later in this section. a simple code example implementing the de sired behavior is also presented. figure 85. interfacing the application to the twi in a typical transmission 1. the first step in a twi transmission is to transmit a start condition. this is done by writing a specific value into twcr, instructing the twi hardware to transmit a start condition. which value to write is described later on. however, it is important that the twint bit is se t in the value written. writing a one to twint clears the flag. the twi will not start any operation as long as the twint bit in twcr is set. immediatel y after the application has cleared twint, the twi will initiate transmission of the start condition. 2. when the start condition has been transmitted, the twint flag in twcr is set, and twsr is updated with a status code indicating that the start condition has successfully been sent. 3. the application software should now examine the value of twsr, to make sure that the start condition was successfully transmitted. if twsr indicates other- wise, the application software might ta ke some special action, like calling an error routine. assuming that the status code is as expected, the application must start sla+w a data a stop 1. application writes to twcr to initiate transmission of start 2. twint set. status code indicates start condition sent 4. twint set. status code indicates sla+w sent, ack received 6. twint set. status code indicates data sent, ack received 3. check twsr to see if start was sent. application loads sla+w into twdr, and loads appropriate control signals into twcr, making sure that twint is written to one, and twsta is written to zero. 5. check twsr to see if sla+w was sent and ack received. application loads data into twdr, and loads appropriate control signals into twcr, making sure that twint is wwritten to one. 7. check twsr to see if data was sent and ack received. application loads appropriate control signals to send stop into twcr, making sure that twint is written to one. twi bus indicates twint set application action twi hardware action
186 atmega8535(l) 2502k?avr?10/06 load sla+w into twdr. remember that twdr is used both for address and data. after twdr has been loaded with the desired sla+w, a specific value must be written to twcr, instructing the twi hardware to transmit the sla+w present in twdr. which value to write is described later on. however, it is important that the twint bit is set in the value written. writing a one to twint clears the flag. the twi will not start any operation as long as the twint bit in twcr is set. immediately after the ap plication has cleared twint, the twi will initiate transmission of the address packet. 4. when the address packet has been transmitted, the twint flag in twcr is set, and twsr is updated with a status code indicating that the address packet has successfully been sent. the status co de will also reflect whether a slave acknowledged the packet or not. 5. the application software should now examine the value of twsr, to make sure that the address packet was successfully transmitted, and that the value of the ack bit was as expected. if twsr indicates otherwise, the application software might take some special action, like callin g an error routine. assuming that the status code is as expected, the application must load a data packet into twdr. subsequently, a specific value must be written to twcr, instructing the twi hardware to transmit the data packet present in twdr. the value which to write is described later on. however, it is im portant that the twint bit is set in the value written. writing a one to twint clears the flag. the twi will not start any operation as long as the twint bit in twcr is set. immediately after the appli- cation has cleared twint, the twi will init iate transmission of the data packet. 6. when the data packet has been transmitted, the twint flag in twcr is set, and twsr is updated with a status code indicating that the data packet has suc- cessfully been sent. the status co de will also reflect whether a slave acknowledged the packet or not. 7. the application software should now examine the value of twsr, to make sure that the data packet was successfully transmitted, and that the value of the ack bit was as expected. if twsr indicates otherwise, the application software might take some special action, like calling an error routine. assu ming that the status code is as expected, the application must write a specific value to twcr, instructing the twi hardware to transmit a stop condition. which value to write is described later on. however, it is im portant that the twint bit is set in the value written. writing a one to twint clears the flag. the twi will not start any operation as long as the twint bit in twcr is set. immediately after the appli- cation has cleared twint, the twi will initiate transmission of the stop condition. note that twint is not set after a stop condition has been sent. even though this example is simple, it shows th e principles involved in all twi transmis- sions. these can be summarized as follows: ? when the twi has finished an operation and expects application response, the twint flag is set. the scl line is pulled low until twint is cleared. ? when the twint flag is set, the user must update all twi registers with the value relevant for the next twi bus cycle. as an example, twdr must be loaded with the value to be transmitted in the next bus cycle. ? after all twi register updates and other pending application software tasks have been completed, twcr is written. when writing twcr, the tw int bit should be set. writing a one to twint clears the fl ag. the twi will then commence executing whatever operation was specified by the twcr setting.
187 atmega8535(l) 2502k?avr?10/06 in the following an assembly and c implement ation of the example is given. note that the code below assumes that several definitions have been made, for example by using include-files. assembly code example c example comments 1 ldi r16, (1< 188 atmega8535(l) 2502k?avr?10/06 transmission modes the twi can operate in one of four major modes. these are named master transmitter (mt), master receiver (mr), slave transmit ter (st), and slave receiver (sr). several of these modes can be used in the same appl ication. as an example, the twi can use mt mode to write data into a twi eeprom, mr mode to read the data back from the eeprom. if other masters are present in the sy stem, some of these might tran smit data to the twi, and then sr mode would be used. it is the application software that decides which modes are legal. the following sections describe each of these modes. possible status codes are described along with figures detailing data tran smission in each of the modes. these fig- ures contain the following abbreviations: s: start condition rs: repeated start condition r: read bit (high level at sda) w: write bit (low level at sda) a: acknowledge bit (low level at sda) a : not acknowledge bit (high level at sda) data: 8-bit data byte p: stop condition sla: slave address in figure 87 to figure 93, circles are used to indicate that the twint flag is set. the numbers in the circles show the status code held in twsr, with the prescaler bits masked to zero. at these points, actions must be taken by the application to continue or complete the twi transfer. the twi transfer is suspended until the twint flag is cleared by software. when the twint flag is set, the status code in twsr is used to determine the appro- priate software action. for each status code, the required software action and details of the following serial transfer are given in table 75 to table 78. note that the prescaler bits are masked to zero in these tables.
189 atmega8535(l) 2502k?avr?10/06 master transmitter mode in the master transmitter mode, a number of data bytes are transmitted to a slave receiver (see figure 86). in order to enter a master mode, a start condition must be transmitted. the format of the following address packet determines whether master transmitter or master receiver mode is to be entered. if sla+w is transmitted, mt mode is entered, if sla+r is transmitted, mr mode is entered. all the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. figure 86. data transfer in ma ster transmitter mode a start condition is sent by wr iting the following value to twcr: twen must be set to enable the two-wire serial interface, twsta must be written to one to transmit a start condition and twint must be written to one to clear the twint flag. the twi will then test the tw o-wire serial bus an d generate a start condition as soon as the bus becomes free. after a start condition has been transmit- ted, the twint flag is set by hardware, and the status code in twsr will be 0x08 (see table 75). in order to enter mt mode, sla+w mu st be transmitted. this is done by writ- ing sla+w to twdr. thereafter the twint bi t should be cleared (by writing it to one) to continue the transfer. this is accomplis hed by writing the fo llowing value to twcr: when sla+w have been transmitted and an acknowledgement bit has been received, twint is set again and a number of status codes in twsr are possible. possible sta- tus codes in master mode are 0x18, 0x20, or 0x38. the appropriate action to be taken for each of these status codes is detailed in table 75. when sla+w has been successfully transmitt ed, a data packet should be transmitted. this is done by writing the data byte to twdr. twdr must only be written when twint is high. if not, the access will be discarded, and the writ e collision bit (twwc) will be set in the twcr register. afte r updating twdr, the twint bit should be cleared (by writing it to one) to continue the transfer. this is acco mplished by writing the following value to twcr: twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x00 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x00 x1 0 x device 1 master transmitter device 2 slave receiver device 3 device n sda scl ........ r1 r2 v cc
190 atmega8535(l) 2502k?avr?10/06 this scheme is repeated until the last byte has been sent and the transfer is ended by generating a stop condition or a repeated start condition. a stop condition is gen- erated by writing the following value to twcr: a repeated start condition is generated by writing the following value to twcr: after a repeated start condition (state 0x10) the two-wire serial interface can access the same slave again, or a new slave without transmitting a stop condition. repeated start enables the master to switch between slaves, master transmitter mode and master receiver mode without losing control of the bus.. twcr twint twea twsta twsto twwc twen ? twie value 1 x01 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x table 75. status codes for master transmitter mode status code (twsr) prescaler bits are 0 status of the two-wire serial bus and two-wire serial inter- face hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea 0x08 a start condition has been transmitted load sla+w 0 0 1 x sla+w will be transmitted; ack or not ack will be received 0x10 a repeated start condition has been transmitted load sla+w or load sla+r 0 0 0 0 1 1 x x sla+w will be transmitted; ack or not ack will be received sla+r will be transmitted; logic will switch to master receiver mode 0x18 sla+w has been transmitted; ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x20 sla+w has been transmitted; not ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x28 data byte has been transmitted; ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x30 data byte has been transmitted; not ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x38 arbitration lost in sla+w or data bytes no twdr action or no twdr action 0 1 0 0 1 1 x x two-wire serial bus will be released and not addressed slave mode entered a start condition will be transmitted when the bus be- comes free
191 atmega8535(l) 2502k?avr?10/06 figure 87. formats and states in the master transmitter mode s sla w a data a p $08 $18 $28 r sla w $10 ap $20 p $30 a or a $38 a other master continues a or a $38 other master continues r a $68 other master continues $78 $b0 to corresponding states in slave mode mt mr successfull transmission to a slave receiver next transfer started with a repeated start condition not acknowledge received after the slave address not acknowledge received after a data byte arbitration lost in slave address or data byte arbitration lost and addressed as slave data a n from master to slave from slave to master any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero s
192 atmega8535(l) 2502k?avr?10/06 master receiver mode in the master receiver mode, a number of data bytes are received from a slave trans- mitter (see figure 88). in order to enter a master mode, a start condition must be transmitted. the format of the following address packet determines whether master transmitter or master receiver mode is to be entered. if sla+w is transmitted, mt mode is entered, if sla+r is transmitted, mr mode is entered. all the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. figure 88. data transfer in master receiver mode a start condition is sent by wr iting the following value to twcr: twen must be written to one to enable the two-wire serial interface, twsta must be written to one to transmit a start condition and twint must be set to clear the twint flag. the twi will then test the two-wire se rial bus and generate a start condition as soon as the bus becomes free. after a start condition has been transmitted, the twint flag is set by hardwa re, and the status code in twsr will be 0x08 (see table 75). in order to enter mr mode, sla+r must be transmitted. this is done by writing sla+r to twdr. thereafter the twint bit should be cleared (by writing it to one) to continue the transfer. this is accomplishe d by writing the following value to twcr: when sla+r have been transmitted and an acknowledgement bit has been received, twint is set again and a number of status codes in twsr are possible. possible sta- tus codes in master mode are 0x38, 0x40, or 0x48. the appropriate action to be taken for each of these status codes is detailed in table 76. received data can be read from the twdr register when the twint flag is set high by hardware. this scheme is repeated until the last byte has been received. after the last byte has been received, the mr should inform the st by sending a nack after the last received data byte. the transfer is ended by generating a stop c ondition or a repeated start condition. a stop condition is generated by wr iting the following value to twcr: twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x00 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x01 x1 0 x device 1 master receiver device 2 slave transmitter device 3 device n sda scl ........ r1 r2 v cc
193 atmega8535(l) 2502k?avr?10/06 a repeated start condition is generated by writing the following value to twcr: after a repeated start condition (state 0x10) the two-wire serial interface can access the same slave again, or a new slave without transmitting a stop condition. repeated start enables the master to switch between slaves, master transmitter mode and master receiver mode without losing control over the bus. twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x table 76. status codes for master receiver mode status code (twsr) prescaler bits are 0 status of the two-wire serial bus and two-wire serial inter- face hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea 0x08 a start condition has been transmitted load sla+r 0 0 1 x sla+r will be transmitted ack or not ack will be received 0x10 a repeated start condition has been transmitted load sla+r or load sla+w 0 0 0 0 1 1 x x sla+r will be transmitted ack or not ack will be received sla+w will be transmitted logic will switch to master transmitter mode 0x38 arbitration lost in sla+r or not ack bit no twdr action or no twdr action 0 1 0 0 1 1 x x two-wire serial bus will be released and not addressed slave mode will be entered a start condition will be transmitted when the bus becomes free 0x40 sla+r has been transmitted; ack has been received no twdr action or no twdr action 0 0 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x48 sla+r has been transmitted; not ack has been received no twdr action or no twdr action or no twdr action 1 0 1 0 1 1 1 1 1 x x x repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x50 data byte has been received; ack has been returned read data byte or read data byte 0 0 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x58 data byte has been received; not ack has been returned read data byte or read data byte or read data byte 1 0 1 0 1 1 1 1 1 x x x repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset
194 atmega8535(l) 2502k?avr?10/06 figure 89. formats and states in the master receiver mode slave receiver mode in the slave receiver mode, a number of data bytes are received from a master trans- mitter (see figure 90). all the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. figure 90. data transfer in slave receiver mode s sla r a data a $08 $40 $50 sla r $10 ap $48 a or a $38 other master continues $38 other master continues w a $68 other master continues $78 $b0 to corresponding states in slave mode mr mt successfull reception from a slave receiver next transfer started with a repeated start condition not acknowledge received after the slave address arbitration lost in slave address or data byte arbitration lost and addressed as slave data a n from master to slave from slave to master any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero p data a $58 a r s device 3 device n sda scl ........ r1 r2 v cc device 2 master transmitter device 1 slave receiver
195 atmega8535(l) 2502k?avr?10/06 to initiate the slave receiver mode, twar and twcr must be initialized as follows: the upper seven bits are the address to wh ich the two-wire serial interface will respond when addressed by a master. if the lsb is set, the twi will respond to the general call address (0x00), otherwise it will ignore the general call address. twen must be written to one to enable the twi. the twea bit must be written to one to enable the acknowledgement of the device?s own slave address or the general call address. twsta and twsto must be written to zero. when twar and twcr have been initialized, th e twi waits until it is addressed by its own slave address (or the general call address if enabled) followed by the data direction bit. if the direction bit is ?0? (write), the twi will operate in sr mode, otherwise st mode is entered. after its own slave address and the write bit have been received, the twint flag is set and a valid status code can be read from twsr. the status code is used to determine the appropriate software action. the appropriate action to be taken for each status code is detailed in table 77. the slave receiver mode may also be entered if arbitration is lost while the twi is in the master mode (see states 0x68 and 0x78). if the twea bit is reset during a transfer, the twi will return a ?not acknowledge? (?1?) to sda after the next received data byte. this can be used to indicate that the slave is not able to receive any more bytes. while twea is zero, the twi does not acknowledge its own slave address. howeve r, the two-wire serial bus is still monitore d and address recognition may resume at any time by setting twea. this implies that the twea bit may be used to temporarily isolate the twi from the two-wire serial bus. in all sleep modes other than idle mode, the clock system to the twi is turned off. if the twea bit is set, the interfac e can still acknowledge its own slave address or the general call address by using the two-wire serial bu s clock as a clock source. the part will then wake up from sleep and the twi will hold the scl clock low during the wake up and until the twint flag is cleared (by writing it to one). furt her data recept ion will be car- ried out as normal, with the avr clocks running as normal. observe that if the avr is set up with a long start-up time, the scl line may be held low for a long time, blocking other data transmissions. note that the two-wire serial interface data register ? twdr ? does not reflect the last byte present on the bus when waking up from these sleep modes. twar twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce value device?s own slave address twcr twint twea twsta twsto twwc twen ? twie value 0 100 01 0 x
196 atmega8535(l) 2502k?avr?10/06 table 77. status codes for slave receiver mode status code (twsr) prescaler bits are 0 status of the two-wire serial bus and two-wire serial interface hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea 0x60 own sla+w has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x68 arbitration lost in sla+r/w as master; own sla+w has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x70 general call address has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x78 arbitration lost in sla+r/w as master; general call address has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x80 previously addressed with own sla+w; data has been received; ack has been returned read data byte or read data byte x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x88 previously addressed with own sla+w; data has been received; not ack has been returned read data byte or read data byte or read data byte or read data byte 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free 0x90 previously addressed with general call; data has been re- ceived; ack has been returned read data byte or read data byte x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x98 previously addressed with general call; data has been received; not ack has been returned read data byte or read data byte or read data byte or read data byte 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free 0xa0 a stop condition or repeated start condition has been received while still addressed as slave no action 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free
197 atmega8535(l) 2502k?avr?10/06 figure 91. formats and states in the slave receiver mode s sla w a data a $60 $80 $88 a $68 reception of the own slave address and one or more data bytes. all are acknowledged last data byte received is not acknowledged arbitration lost as master and addressed as slave reception of the general call address and one or more data bytes last data byte received is not acknowledged n from master to slave from slave to master any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero p or s data a $80 $a0 p or s a a data a $70 $90 $98 a $78 p or s data a $90 $a0 p or s a general call arbitration lost as master and addressed as slave by general call data a
198 atmega8535(l) 2502k?avr?10/06 slave transmitter mode in the slave transmitter mode, a number of data bytes are transmitted to a master receiver (see figure 92). all the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. figure 92. data transfer in slave transmitter mode to initiate the slave transm itter mode, twar and twcr mu st be initialized as follows: the upper seven bits are the address to wh ich the two-wire serial interface will respond when addressed by a master. if the lsb is set, the twi will respond to the general call address (0x00), otherwise it will ignore the general call address. twen must be written to one to enable the twi. the twea bit must be written to one to enable the acknowledgement of the device?s own slave address or the general call address. twsta and twsto must be written to zero. when twar and twcr have been initialized, th e twi waits until it is addressed by its own slave address (or the general call address if enabled) followed by the data direction bit. if the direction bit is ?1? (read), the twi will operate in st mo de, otherwise sr mode is entered. after its own slave address and the write bit have been received, the twint flag is set and a valid status code can be read from twsr. the status code is used to determine the appropriate software action. the appropriate action to be taken for each status code is detailed in table 78. the slave transmitter mode may also be entered if arbitration is lost while the twi is in the master mode (see state 0xb0). if the twea bit is written to zero during a tr ansfer, the twi will tran smit the last byte of the transfer. state 0xc0 or state 0xc8 will be entered, depending on wh ether the master receiver transmits a nack or ack after the final byte. the twi is switched to the not addressed slave mode, and will ignore the master if it continues the transfer. thus the master receiver receives all ?1? as serial data. state 0xc8 is entered if the master demands additional data bytes (by transmitting ack), even though the slave has trans- mitted the last byte (twea zero and expecting nack from the master). while twea is zero, the twi does not respond to its own slave address. however, the two-wire serial bus is still monitored and address recognition may resume at any time twar twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce value device?s own slave address twcr twint twea twsta twsto twwc twen ? twie value 0 100 01 0 x device 3 device n sda scl ........ r1 r2 v cc device 2 master receiver device 1 slave transmitter
199 atmega8535(l) 2502k?avr?10/06 by setting twea. this implies that the twea bit may be used to temporarily isolate the twi from the two-wire serial bus. in all sleep modes other than idle mode, the clock system to the twi is turned off. if the twea bit is set, the interfac e can still acknowledge its own slave address or the general call address by using the two-wire serial bu s clock as a clock source. the part will then wake up from sleep and the twi will hold t he scl clock will low during the wake up and until the twint flag is cleared (by writing it to one). further data transmission will be carried out as normal, with the avr clocks running as normal. observe that if the avr is set up with a long start-up time, the scl line may be held low for a long time, blocking other data transmissions. note that the two-wire serial interface data register ? twdr ? does not reflect the last byte present on the bus when waking up from these sleep modes. table 78. status codes for slave transmitter mode status code (twsr) prescaler bits are 0 status of the two-wire serial bus and two-wire serial interface hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea 0xa8 own sla+r has been received; ack has been returned load data byte or load data byte x x 0 0 1 1 0 1 last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be re- ceived 0xb0 arbitration lost in sla+r/w as master; own sla+r has been received; ack has been returned load data byte or load data byte x x 0 0 1 1 0 1 last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be re- ceived 0xb8 data byte in twdr has been transmitted; ack has been received load data byte or load data byte x x 0 0 1 1 0 1 last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be re- ceived 0xc0 data byte in twdr has been transmitted; not ack has been received no twdr action or no twdr action or no twdr action or no twdr action 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free 0xc8 last data byte in twdr has been transmitted (twea = ?0?); ack has been received no twdr action or no twdr action or no twdr action or no twdr action 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free
200 atmega8535(l) 2502k?avr?10/06 figure 93. formats and states in the slave transmitter mode miscellaneous states there are two status codes that do not correspond to a defined twi state, see table 79. status 0xf8 indicates that no relevant info rmation is available because the twint flag is not set. this occurs between other states, and when the twi is not involved in a serial transfer. status 0x00 indicates that a bus error has occurred during a two-wire serial bus trans- fer. a bus error occurs when a start or stop condition occurs at an illegal position in the format frame. examples of such illegal positions are during the serial transfer of an address byte, a data byte, or an acknowledge bit. when a bus error occurs, twint is set. to recover from a bus error, the twsto flag must set and twint must be cleared by writing a logic one to it. this causes the twi to enter the not addressed slave mode and to clear the twsto flag (no other bits in twcr are affected). the sda and scl lines are released, and no stop condition is transmitted. s sla r a data a $a8 $b8 a $b0 reception of the own slave address and one or more data bytes last data byte transmitted. switched to not addressed slave (twea = '0') arbitration lost as master and addressed as slave n from master to slave from slave to master any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero p or s data $c0 data a a $c8 p or s all 1's a table 79. miscellaneous states status code (twsr) prescaler bits are 0 status of the two-wire serial bus and two-wire serial inter- face hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea 0xf8 no relevant state information available; twint = ?0? no twdr action no twcr action wait or proceed current transfer 0x00 bus error due to an illegal start or stop condition no twdr action 0 1 1 x only the internal hardware is affected, no stop condi- tion is sent on the bus. in all cases, the bus is released and twsto is cleared.
201 atmega8535(l) 2502k?avr?10/06 combining several twi modes in some cases, several twi modes must be combined in or der to complete the desired action. consider for example reading data from a serial eeprom. typically, such a transfer involves the following steps: 1. the transfer must be initiated. 2. the eeprom must be instructed what location should be read. 3. the reading must be performed. 4. the transfer must be finished. note that data is transmitted both from master to slave and vice versa. the master must instruct the slave what location it wants to read, requiring the use of the mt mode. sub- sequently, data must be read from the slave, implying the use of the mr mode. thus, the transfer direction must be changed. the master must keep control of the bus during all these steps, and the steps should be carried out as an atomical operation. if this prin- ciple is violated in a multimaster system, another master can alter the data pointer in the eeprom between steps 2 and 3, and the master will read the wrong data location. such a change in transfer direction is accomplished by transmitting a repeated start between the transmission of the address byte and reception of the data. after a repeated start, the master keeps ownership of the bus. the following figure shows the flow in this transfer. figure 94. combining several twi modes to access a serial eeprom multi-master systems and arbitration if multiple masters are connected to the sa me bus, transmissions may be initiated simul- taneously by one or more of them. the twi standard ensures that such situations are handled in such a way that one of the master s will be allowed to pr oceed with the trans- fer, and that no data will be lost in the process. an example of an arbitration situation is depicted below, where two masters are trying to transmit data to a slave receiver. figure 95. an arbitration example master transmitter master receiver s = start rs = repeated start p = stop transmitted from master to slave transmitted from slave to master s sla+w a address a rs sla+r a data a p device 1 master transmitter device 2 master transmitter device 3 slave receiver device n sda scl ........ r1 r2 v cc
202 atmega8535(l) 2502k?avr?10/06 several different scenarios may arise during arbitration, as described below: ? two or more masters are performing identical communication with the same slave. in this case, neither the slave nor an y of the masters will know about the bus contention. ? two or more masters are accessing the same slave with different data or direction bit. in this case, arbitration will occur, eith er in the read/write bit or in the data bits. the masters trying to output a one on sda while another master outputs a zero will lose the arbitration. losing masters will switch to not addre ssed slave mode or wait until the bus is free and transmit a new start condition, depending on application software action. ? two or more masters are accessing differ ent slaves. in this case, arbitration will occur in the sla bits. masters trying to output a one on sda while another master outputs a zero will lose the arbitration. masters losing ar bitration in sla will switch to slave mode to check if they are being addressed by the winning master. if addressed, they will switch to sr or st mode, depending on the value of the read/write bit. if they are not being add ressed, they will switch to not addressed slave mode or wait until the bus is free and transmit a new start condition, depending on application software action. this is summarized in figure 96. possibl e status values are given in circles. figure 96. possible status codes caused by arbitration own address / general call received arbitration lost in sla twi bus will be released and not addressed slave mode will be entered a start condition will be transmitted when the bus becomes free no arbitration lost in data direction ye s write data byte will be received and not ack will be returned data byte will be received and ack will be returned last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be received read b0 68/78 38 sla start data stop
203 atmega8535(l) 2502k?avr?10/06 analog comparator the analog comparator compares the input values on the positive pin ain0 and nega- tive pin ain1. when the voltage on the positive pin ain0 is higher than the voltage on the negative pin ain1, the analog comparator output, aco, is set. the comparator?s output can be set to trigger the timer/counter1 input capture function. in addition, the comparator can trigger a separate interrupt, exclusive to the analog comparator. the user can select interrupt triggering on comparator output rise, fall or toggle. a block dia- gram of the comparator and its surrounding logic is shown in figure 97 . figure 97. analog comparator block diagram (2) notes: 1. see table 81 on page 205. 2. refer to figure 1 on page 2 and table 26 on page 60 for analog comparator pin placement. special function io register ? sfior ? bit 3 ? acme: analog comparator multiplexer enable when this bit is written logic one and the adc is switched off (aden in adcsra is zero), the adc multiplexer selects the negative input to the analog comparator. when this bit is written logic zero, ain1 is applied to the negative input of the analog compar- ator. for a detailed description of this bit, see ?analog comparator multiplexed input? on page 205. analog comparator control and status register ? acsr ? bit 7 ? acd: analog comparator disable when this bit is written logic one, the power to the analog comparator is switched off. this bit can be set at any time to turn o ff the analog comparator . this will reduce power consumption in active and idle mode. when changing the acd bit, the analog compar- acbg bandgap reference adc multiplexer output acme aden (1) bit 7 6 5 4 3 2 1 0 adts2 adts1 adts0 ? acme pud psr2 psr10 sfior read/write r/w r/w r/w r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 acd acbg aco aci acie acic acis1 acis0 acsr read/write r/w r/w r r/w r/w r/w r/w r/w initial value 0 0 n/a 0 0 0 0 0
204 atmega8535(l) 2502k?avr?10/06 ator interrupt must be disabled by clearing t he acie bit in acsr. otherwise an interrupt can occur when the bit is changed. ? bit 6 ? acbg: analog comparator bandgap select when this bit is set, a fixed bandgap referenc e voltage replaces the positive input to the analog comparator. when this bit is cleared, ain0 is applied to the positive input of the analog comparator. see ?internal voltage reference? on page 41. ? bit 5 ? aco: analog comparator output the output of the analog comparator is synchronized and then directly connected to aco. the synchronization introduces a delay of 1 - 2 clock cycles. ? bit 4 ? aci: analog comparator interrupt flag this bit is set by hardware when a comparator output event triggers the interrupt mode defined by acis1 and acis0. the analog comparator interrupt routine is executed if the acie bit is set and the i-bit in sreg is set. aci is cleared by hardware when execut- ing the corresponding interrupt handling vector. alternatively, aci is cleared by writing a logic one to the flag. ? bit 3 ? acie: analog comparator interrupt enable when the acie bit is written logic one and the i-bit in the status register is set, the ana- log comparator interrupt is activated. when written logic zero, the interrupt is disabled. ? bit 2 ? acic: analog comparator input capture enable when written logic one, this bit enables the input capture function in timer/counter1 to be triggered by the analog comparator. the comparator output is in this case directly connected to the input capture front-end logic, making the comparator utilize the noise canceler and edge select features of the timer/counter1 input capture interrupt. when written logic zero, no connection between the analog comparator and the input capture function exists. to make the comparator tr igger the timer/counter1 input capture inter- rupt, the ticie1 bit in the timer interrupt mask register (timsk) must be set. ? bits 1, 0 ? acis1, acis0: analog comparator interrupt mode select these bits determine which comparator events that trigger the analog comparator inter- rupt. the different settings are shown in table 80. when changing the acis1/acis0 bits, the anal og comparator interrupt must be dis- abled by clearing its interrupt enable bit in the acsr register. otherwise an interrupt can occur when the bits are changed. table 80. acis1/acis0 settings acis1 acis0 interrupt mode 0 0 comparator interrupt on output toggle 01reserved 1 0 comparator interrupt on falling output edge 1 1 comparator interrupt on rising output edge
205 atmega8535(l) 2502k?avr?10/06 analog comparator multiplexed input it is possible to select any of the adc7..0 pins to replace the negative input to the ana- log comparator. the adc multiple xer is used to select this input, and consequently, the adc must be switched off to utilize this feature. if the analog comparator multiplexer enable bit (acme in sfior) is set and the adc is switched off (aden in adcsra is zero), mux2..0 in admux select the input pin to replace the negative input to the ana- log comparator, as shown in table 81. if ac me is cleared or aden is set, ain1 is applied to the negative input to the analog comparator. table 81. analog comparator multiplexed input acme aden mux2..0 analog comparator negative input 0 x xxx ain1 1 1 xxx ain1 1 0 000 adc0 1 0 001 adc1 1 0 010 adc2 1 0 011 adc3 1 0 100 adc4 1 0 101 adc5 1 0 110 adc6 1 0 111 adc7
206 atmega8535(l) 2502k?avr?10/06 analog-to-digital converter features ? 10-bit resolution ? 0.5 lsb integral non-linearity ? 2 lsb absolute accuracy ? 65 - 260 s conversion time ? up to 15 ksps at maximum resolution ? 8 multiplexed single ended input channels ? 7 differential input channels ? 2 differential input channels with optional gain of 10x and 200x (1) ? optional left adjustment for adc result readout ? 0 - v cc adc input voltage range ? selectable 2.56v adc reference voltage ? free running or single conversion mode ? adc start conversion by auto triggering on interrupt sources ? interrupt on adc co nversion complete ? sleep mode noise canceler note: 1. the differential input channel are not tested for devices in pdip and plcc package. this feature is only guaranteed to work for devices in tqfp and qfn/mlf packages. the atmega8535 features a 10-bit successive approximation adc. the adc is con- nected to an 8-channel analog multiplexer which allows eight single-ended voltage inputs constructed from the pins of port a. the single-ended voltage inputs refer to 0v (gnd). the device also supports 16 differential voltage input combinations. two of the differen- tial inputs (adc1, adc0 and adc3, adc2) are equipped with a programmable gain stage, providing amplification steps of 0 db (1x), 20 db (10x), or 46 db (200x) on the dif- ferential input voltage before the a/d c onversion. seven differential analog input channels share a common negative terminal (adc1), while any other adc input can be selected as the positive input terminal. if 1x or 10x gain is used, 8-bit resolution can be expected. if 200x gain is used, 7-bit resolution can be expected. the adc contains a sample and hold circuit which ensures that the input voltage to the adc is held at a constant level during conv ersion. a block diagram of the adc is shown in figure 98. the adc has a separate analog supply voltage pin, avcc. avcc must not differ more than 0.3v from v cc . see the paragraph ?adc noise canceler? on page 214 on how to connect this pin. internal reference voltages of nominally 2. 56v or avcc are provided on-chip. the volt- age reference may be externally decoupled at the aref pin by a capacitor for better noise performance.
207 atmega8535(l) 2502k?avr?10/06 figure 98. analog-to-digital converter block schematic operation the adc converts an analog input voltage to a 10-bit digital value through successive approximation. the minimum value represents gnd and the maximum value represents the voltage on the aref pin minus 1 lsb. optionally, avcc or an internal 2.56v refer- ence voltage may be connected to the aref pin by writing to the refsn bits in the admux register. the internal voltage refere nce may thus be decoupled by an external capacitor at the aref pin to improve noise immunity. the analog input channel and differential gain are selected by writing to the mux bits in admux. any of the adc input pins, as we ll as gnd and a fixed bandgap voltage refer- ence, can be selected as single ended inputs to the adc. a selection of adc input pins can be selected as positive and negative i nputs to the differential gain amplifier. if differential channels are selected, the differential gain stage amplifies the voltage dif- ference between the selected input channel pair by the selected gain factor. this amplified value then becomes the analog input to the adc. if single ended channels are used, the gain amplifier is bypassed altogether. adc conversion complete irq 8-bit data bus 15 0 adc multiplexer select (admux) adc ctrl. & status register (adcsra) adc data register (adch/adcl) mux2 adie adate adsc aden adif adif mux1 mux0 adps0 adps1 adps2 mux3 conversion logic 10-bit dac + - sample & hold comparator internal 2.56v reference mux decoder mux4 avcc adc7 adc6 adc5 adc4 adc3 adc2 adc1 adc0 refs0 refs1 adlar + - channel selection gain selection adc[9:0] adc multiplexer output gain amplifier aref bandgap reference prescaler single ended / differential selection gnd pos. input mux neg. input mux trigger select adts[2:0] interrupt flags start
208 atmega8535(l) 2502k?avr?10/06 the adc is enabled by setting the adc enable bit, aden in adcsra. voltage refer- ence and input ch annel selections will not go into e ffect until aden is set. the adc does not consume power when aden is cleared, so it is recommended to switch off the adc before entering power saving sleep modes. the adc generates a 10-bit result which is presented in the adc data registers, adch and adcl. by default, the result is presented right adjusted, but can optionally be presented left adjusted by setting the adlar bit in admux. if the result is left adjusted and no more than 8-bit precision is requir ed, it is sufficient to read adch. otherwise, adcl must be read fi rst, then adch, to en sure that the content of the data registers belongs to the same conversion. once adcl is read, adc access to data registers is blocked. this means that if adcl has been read, and a conversion completes before adch is read, neither register is updated and the result from the con- version is lost. when adch is read, adc access to the adch and adcl registers is re-enabled. the adc has its own interrupt which can be triggered when a conversion completes. when adc access to the data registers is prohibited between reading of adch and adcl, the interrupt will trigger even if t he result is lost. starting a conversion a single conversion is started by writing a logical one to the adc start conversion bit, adsc. this bit stays high as long as the co nversion is in progress and will be cleared by hardware when the conversion is completed. if a different data channel is selected while a conversion is in progress, the adc will fi nish the current conver sion before performing the channel change. alternatively, a conversion can be triggered automatically by various sources. auto trig- gering is enabled by setting the adc auto trigger enable bit, adate in adcsra. the trigger source is selected by setting the adc trigger select bits, adts in sfior (see description of the adts bits for a list of the trigger sources). when a positive edge occurs on the selected trigger signal, the adc prescaler is reset and a conversion is started. this provides a method of starting c onversions at fixed intervals. if the trigger signal still is set when the conversion comple tes, a new conversion will not be started. if another positive edge occurs on the trigger signal during conversion, the edge will be ignored. note that an interrupt flag will be set even if the s pecific interrupt is disabled or the global interrupt enable bit in sreg is cleared. a conversion can thus be triggered without causing an interrupt. however, the interrupt flag must be cleared in order to trig- ger a new conversion at the next interrupt event.
209 atmega8535(l) 2502k?avr?10/06 figure 99. adc auto trigger logic using the adc interrupt flag as a trigger source makes the adc start a new conversion as soon as the ongoing conversion has finished. the adc then operates in free run- ning mode, constantly sampling and updating the adc data register. the first conversion must be started by writing a logical one to the adsc bit in adcsra. in this mode the adc will perform successive c onversions independently of whether the adc interrupt flag, adif is cleared or not. if auto triggering is enabled, single conversions can be started by writing adsc in adcsra to one. adsc can also be used to determine if a conversion is in progress. the adsc bit will be read as one during a conversion, indep endently of how the conver- sion was started. prescaling and conversion timing figure 100. adc prescaler by default, the successive approximation circuitry requires an input clock frequency between 50 khz and 200 khz to get maximum resolution. if a lower resolution than 10 bits is needed, the input clock frequency to the adc can be higher than 200 khz to get a higher sample rate. adsc adif source 1 source n adts[2:0] conversion logic prescaler start clk adc . . . . edge detector adate 7-bit adc prescaler adc clock source ck adps0 adps1 adps2 ck/128 ck/2 ck/4 ck/8 ck/16 ck/32 ck/64 reset aden start
210 atmega8535(l) 2502k?avr?10/06 the adc module contains a prescaler, which generates an acceptable adc clock fre- quency from any cpu frequency above 100 khz. the prescaling is set by the adps bits in adcsra. the prescaler starts counting from the moment the adc is switched on by setting the aden bit in adcsra. the prescaler keeps running for as long as the aden bit is set, and is continuously reset when aden is low. when initiating a single ended conversion by setting the adsc bit in adcsra, the con- version starts at the following rising edge of the adc clock cycle. see ?differential gain channels? on page 212 for details on differential conversion timing. a normal conversion takes 13 adc clock cycl es. the first conversion after the adc is switched on (aden in adcsra is set) takes 25 adc clock cycles in order to initialize the analog circuitry. the actual sample-and-hold takes place 1.5 adc clock cycles after the start of a normal conversion and 13.5 adc clock cycles after th e start of an first conversion. when a con- version is complete, the result is written to the adc data registers, and adif is set. in single conversion mode, adsc is cleared simultaneously. the software may then set adsc again, and a new conver sion will be initiated on the fi rst rising adc clock edge. when auto triggering is used, the prescaler is reset when the trigger event occurs. this assures a fixed delay from the trigger event to the start of conversion. in this mode, the sample-and-hold takes place two adc clock cycl es after the rising edge on the trigger source signal. three additional cpu clock cycles are used for synchronization logic. in free running mode, a new co nversion will be started im mediately afte r the conver- sion completes, while adsc remains high. for a summary of conversion times, see table 82. figure 101. adc timing diagram, first conversion (single conversion mode) msb of result lsb of result adc clock adsc sample & hold adif adch adcl cycle number aden 1 212 13 14 15 16 17 18 19 20 21 22 23 24 25 1 2 first conversion next conversion 3 mux and refs update mux and refs update conversion complete
211 atmega8535(l) 2502k?avr?10/06 figure 102. adc timing diagram, single conversion figure 103. adc timing diagram, auto triggered conversion figure 104. adc timing diagram, free running conversion 1 2 3 4 5 6 7 8 9 10 11 12 13 msb of result lsb of result adc clock adsc adif adch adcl cycle number 12 one conversion next conversion 3 sample & hold mux and refs update conversion complete mux and refs update 1 2 3 4 5 6 7 8 9 10 11 12 13 msb of result lsb of result adc clock trigger source adif adch adcl cycle number 12 one conversion next conversion conversion complete prescaler reset adate prescaler reset sample & hold mux and refs update 11 12 13 msb of result lsb of result adc clock adsc adif adch adcl cycle number 12 one conversion next conversion 34 conversion complete sample & hold mux and refs update
212 atmega8535(l) 2502k?avr?10/06 note: 1. depending on the state of ck adc2 . differential gain channels when using differential gain channels, certai n aspects of the conversion need to be taken into consideration. differential conversions are synchronized to the internal clock ck adc2 equal to half the adc clock. this synchronization is done automat ically by the adc interface in such a way that the sample-and-hold occurs at a specific phase of ck adc2 . a conversion initi- ated by the user (i.e., all single conversi ons, and the first free running conversion) when ck adc2 is low will take the same amount of time as a single ended conversion (13 adc clock cycles from the next prescaled clock cycle). a conversion initiated by the user when ck adc2 is high will take 14 adc clock cycl es due to the synch ronization mecha- nism. in free running mode, a new conversion is initiated immediately after the previous conversion completes, and since ck adc2 is high at this time, all automatically started (i.e., all but the first) free running co nversions will take 14 adc clock cycles. the gain stage is optimized for a bandwidth of 4 khz at all gain settings. higher frequen- cies may be subjected to non-linear amplificat ion. an external low-pass filter should be used if the input signal contains higher frequency components than the gain stage band- width. note that the adc clock frequency is independent of the gain stage bandwidth limitation. for example, the adc clock pe riod may be 6 s, allowing a channel to be sampled at 12 ksps, regardless of the bandwidth of this channel. if differential gain channels are used and conversions are started by auto triggering, the adc must be switched off between conversi ons. when auto triggering is used, the adc prescaler is reset before the conversion is started. since the gain stage is depen- dent of a stable adc clock prior to the conv ersion, this conversion will not be valid. by disabling and then re-enabling the adc between each conversion (writing aden in adcsra to ?0? then to ?1?), only extended conversions are performed. the result from the extended conversions will be valid. see ?prescaling and conversion timing? on page 209 for timing details. changing channel or reference selection the muxn and refs1:0 bits in the admux register are single buffered through a tem- porary register to which the cpu has random access. this ensures that the channels and reference selection only takes place at a safe point during the conversion. the channel and reference selection is continuously updated until a conversion is started. once the conversion starts, the channel and reference selection is locked to ensure a sufficient sampling time for the adc. c ontinuous updating resumes in the last adc clock cycle before the conversion completes (a dif in adcsra is set). note that the conversion starts on the following rising adc clock edge after adsc is written. the user is thus advised not to write new channel or reference selection values to admux until one adc clock cycle after adsc is written. if auto triggering is used, the exact time of the triggering event can be indeterminable. special care must be taken when updating the admux register, in order to control which conversion will be affe cted by the new settings. table 82. adc conversion time condition sample & hold (cycles from start of conversion) conversion time (cycles) first conversion 14.5 25 normal conversions, single ended 1.5 13 auto triggered conversions 2 13.5 normal conversions, differential 1.5/2.5 (1) 13/14 (1)
213 atmega8535(l) 2502k?avr?10/06 if both adate and aden is written to one, an interrupt event can occur at any time. if the admux register is changed in this period, the user cannot tell if the next conversion is based on the old or the new settings. admux can be safely updated in the following ways: 1. when adate or aden is cleared. 2. during conversion, minimum one adc clock cycle after the trigger event. 3. after a conversion, before the interrupt flag used as trigger source is cleared. when updating admux in one of these conditions, the new settings will affect the next adc conversion. special care should be taken when changing differential channels. once a differential channel has been selected, the gain sta ge may take as much as 125 s to stabilize to the new value. thus conversions should not be started within the first 125 s after selecting a new differential channel. alternatively, conversion results obtained within this period should be discarded. the same settling time should be observed for the first differential conversion after changing adc reference (by changi ng the refs1:0 bits in admux). adc input channels when changing channel selections, the user should observe the following guidelines to ensure that the correct channel is selected: in single conversion mode, always select the channel before starting the conversion. the channel selection may be changed one adc clock cycle af ter writing one to adsc. however, the simplest method is to wait for the conversion to complete before changing the channel selection. in free running mode, always select the channel before starting the first conversion. the channel selection may be changed one adc clock cycle af ter writing one to adsc. however, the simplest method is to wait for the first conversion to complete, and then change the channel selection. since the next conversion has already started automati- cally, the next result will reflect the previo us channel selection. subsequent conversions will reflect the new channel selection. when switching to a differential gain channel, the first conversion result may have a poor accuracy due to the required settling time for the automatic offset cancellation cir- cuitry. the user should preferably disregard the first conversion result. adc voltage reference the reference voltage for the adc (v ref ) indicates the conversion range for the adc. single ended channels that exceed v ref will result in codes close to 0x3ff. v ref can be selected as either avcc, internal 2.56v reference, or external aref pin. avcc is connected to the adc through a passive switch. the internal 2.56v reference is generated from the internal bandgap reference (v bg ) through an internal amplifier. in either case, the external aref pin is dire ctly connected to the adc, and the reference voltage can be made more immune to noise by connecting a capacitor between the aref pin and ground. v ref can also be measured at the aref pin with a high impedant voltmeter. note that v ref is a high impedant source, and only a capacitive load should be connected in a system. if the user has a fixed voltage source connected to the aref pin, the user may not use the other reference voltage options in the application, as they will be shorted to the external voltage. if no external voltage is applied to the aref pin, the user may switch between avcc and 2.56v as reference selection. the first adc conversion result after switching reference voltage source may be i naccurate, and the user is advised to dis- card this result.
214 atmega8535(l) 2502k?avr?10/06 if differential channels are used, the select ed reference should not be closer to avcc than indicated in table 114 on page 263 and table 115 on page 264. adc noise canceler the adc features a noise canceler that enables conversion during sleep mode to reduce noise induced from the cpu core and other i/o peripherals. the noise canceler can be used with adc noise reduction and idle mode. to make use of this feature, the following procedure should be used: 1. make sure that the adc is enabled and is not busy converting. single con- version mode must be selected and the adc conversion complete interrupt must be enabled. 2. enter adc noise reduction mode (or idle mode). the adc will start a con- version once the cpu has been halted. 3. if no other interrupts occur before the adc conversion completes, the adc interrupt will wake up the cpu and ex ecute the adc conversion complete interrupt routine. if another interrupt wakes up the cpu before the adc con- version is complete, that interrupt will be executed, and an adc conversion complete interrupt request will be ge nerated when the adc conversion completes. the cpu will remain in ac tive mode until a new sleep command is executed. note that the adc will not be automatically tu rned off when entering other sleep modes than idle mode and adc nois e reduction mode. the user is advised to write zero to aden before entering such sleep modes to av oid excessive power consumption. if the adc is enabled in such sleep modes and the user wants to perform differential conver- sions, the user is advised to switch the adc off and on after waking up from sleep to prompt an extended conversion to get a valid result. analog input circuitry the analog input circuitry for single ended channels is illust rated in figure 105. an ana- log source applied to adcn is subjected to the pin capacitance and input leakage of that pin, regardless of whether that channel is selected as input for the adc. when the chan- nel is selected, the source must drive the s/h capacitor through the series resistance (combined resistance in the input path). the adc is optimized for analog signals with an output impedance of approximately 10 k or less. if such a source is used, the sampling time will be negligible. if a source with higher impedance is used, the sampling time will depend on how long time the source needs to charge the s/h capacitor, wi th can vary widely. the user is recom- mended to only use low impedant sources wit h slowly varying signals, since this minimizes the required charge transfer to the s/h capacitor. if differential gain channels are used, the input circuitry looks somewhat different, although source impedances of a few hundred k or less is recommended. signal components higher than the nyquist frequency (f adc /2) should not be present for either kind of channels, to avoid distortion from unpredictable signal convolution. the user is advised to remove high frequency components with a low-pass filter before applying the signals as inputs to the adc.
215 atmega8535(l) 2502k?avr?10/06 figure 105. analog input circuitry analog noise canceling techniques digital circuitry inside and outside the device generates emi which might affect the accuracy of analog measurements. if conversion accuracy is critical, the noise level can be reduced by applying the following techniques: 1. keep analog signal paths as short as possible. make sure analog tracks run over the analog ground plane, and keep them well away from high-speed switching digital tracks. 2. the avcc pin on the device should be connected to the digital v cc supply voltage via an lc network as shown in figure 106. 3. use the adc noise canceler function to reduce induced noise from the cpu. 4. if any adc port pins are used as digital outputs, it is essential that these do not switch while a conversion is in progress. figure 106. adc power connections adcn i ih 1..100 k c s/h = 14 pf v cc /2 i il gnd vcc pa0 (adc0) pa1 (adc1) pa2 (adc2) pa3 (adc3) pa4 (adc4) pa5 (adc5) pa6 (adc6) pa7 (adc7) aref avcc gnd pc7 10 ? 100nf analog ground plane
216 atmega8535(l) 2502k?avr?10/06 offset compensation schemes the gain stage has a built-in offset cancellation circuitry that nulls the offset of differen- tial measurements as much as possible. the remaining offset in the analog path can be measured directly by selecting the same channe l for both differential inputs. this offset residue can be then subtracted in software from the measurement results. using this kind of software based offset correction, offset on any channel can be reduced below one lsb. adc accuracy definitions an n-bit single-ended adc converts a voltage linearly between gnd and v ref in 2 n steps (lsbs). the lowest code is read as 0, and the highest code is read as 2 n - 1. several parameters describe the deviation from the ideal behavior: ? offset: the deviation of the first transition (0x000 to 0x001) compared to the ideal transition (at 0.5 lsb). ideal value: 0 lsb. figure 107. offset error ? gain error: after adjusting for offset, the gain error is found as the deviation of the last transition (0x3fe to 0x3ff) compared to the ideal transition (at 1.5 lsb below maximum). ideal value: 0 lsb. figure 108. gain error output code v ref input voltage ideal adc actual adc offset error output code v ref input voltage ideal adc actual adc gain error
217 atmega8535(l) 2502k?avr?10/06 ? integral non-linearity (inl): after adjusting for offset and gain error, the inl is the maximum deviation of an actual transition compared to an ideal transition for any code. ideal value: 0 lsb. figure 109. integral non-linearity (inl) ? differential non-linearity ( dnl): the maximum deviation of the actual code width (the interval between two adjacent transitions) from the ideal code width (1 lsb). ideal value: 0 lsb. figure 110. differential non-linearity (dnl) ? quantization error: due to the quantization of the input voltage into a finite number of codes, a range of input voltages (1 l sb wide) will code to the same value. always 0.5 lsb. ? absolute accuracy: the maximum deviation of an actual (unadjusted) transition compared to an ideal transition for any code. this is the compound effect of offset, gain error, differential erro r, non-linearity, and quantization error. ideal value: 0.5 lsb. output code v ref input voltage ideal adc actual adc inl output code 0x3ff 0x000 0 v ref input voltage dnl 1 lsb
218 atmega8535(l) 2502k?avr?10/06 adc conversion result after the conversion is complete (adif is high), the conversion result can be found in the adc result registers (adcl, adch). for single ended conversion, the result is where v in is the voltage on the selected input pin and v ref the selected voltage refer- ence (see table 84 on page 219 and table 85 on page 220). 0x000 represents analog ground, and 0x3ff represents the selected reference voltage minus one lsb. if differential channels are used, the result is where v pos is the voltage on the positive input pin, v neg the voltage on the negative input pin, gain the selected gain factor, and v ref the selected volt age reference. the result is presented in two?s complement form, from 0x200 (-512d) through 0x1ff (+511d). note that if the user wants to perform a quick polarity check of the results, it is sufficient to read the msb of the result (adc 9 in adch). if the bit is one, the result is negative, and if the bit is zero, the result is positive. figure 111 shows the decoding of the differential input range. table 83 shows the resulting output codes if the differential input channel pair (adcn - adcm) is selected with a gain of gain and a reference voltage of v ref . figure 111. differential measurement range adc v in 1024 ? v ref -------------------------- = adc v pos v neg ? () gain 512 ?? v ref ------------------------------------------------------------------------ = 0 output code 0x1ff 0x000 v ref /gain differential input voltage (volts) 0x3ff 0x200 - v ref /gain
219 atmega8535(l) 2502k?avr?10/06 example: admux = 0xed (adc3 - adc2, 10x gain, 2.56v reference, left adjusted result) voltage on adc3 is 300 mv, voltage on adc2 is 500 mv. adcr = 512 * 10 * (300 - 500)/2560 = -400 = 0x270 adcl will thus read 0x00, and adch will read 0x9c. writing zero to adlar right adjusts the result: adcl = 0x70, adch = 0x02. adc multiplexer selection register ? admux ? bit 7:6 ? refs1:0: reference selection bits these bits select the voltage reference for the adc, as shown in table 84. if these bits are changed during a co nversion, the change will not go in effect until this conversion is complete (adif in adcsra is set). the internal voltage reference options may not be used if an external reference voltage is being applied to the aref pin. ? bit 5 ? adlar: adc left adjust result the adlar bit affects the presentation of the adc conversion result in the adc data register. write one to adlar to left adjust the result. otherwise, the result is right adjusted. changing the adlar bit will affe ct the adc data register immediately, regardless of any ongoing conversions. for a complete description of this bit, see ?the adc data register ? adcl and adch? on page 222. table 83. correlation between input voltage and output codes v adcn read code corresponding decimal value v adcm + v ref /gain 0x1ff 511 v adcm + (511/512) v ref /gain 0x1ff 511 v adcm + (510/512) v ref /gain 0x1fe 510 ... ... ... v adcm + (1/512) v ref /gain 0x001 1 v adcm 0x000 0 v adcm - (1/512) v ref /gain 0x3ff -1 ... ... ... v adcm - (511/512) v ref /gain 0x201 -511 v adcm - v ref /gain 0x200 -512 bit 76543210 refs1 refs0 adlar mux4 mux3 mux2 mux1 mux0 admux read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 table 84. voltage reference selections for adc refs1 refs0 voltage reference selection 0 0 aref, internal vref turned off 0 1 avcc with external capacitor at aref pin 10reserved 1 1 internal 2.56v voltage reference with external capacitor at aref pin
220 atmega8535(l) 2502k?avr?10/06 ? bits 4:0 ? mux4:0: analog channel and gain selection bits the value of these bits selects which combination of analog inputs are connected to the adc. these bits also select the gain for the differential channels. see table 85 for details. if these bits are changed during a conv ersion, the change will not go in effect until this conversion is comple te (adif in adcsra is set). table 85. input channel and gain selections mux4..0 single ended input pos different ial input neg differential input gain 00000 adc0 00001 adc1 00010 adc2 00011 adc3 n/a 00100 adc4 00101 adc5 00110 adc6 00111 adc7 01000 adc0 adc0 10x 01001 adc1 adc0 10x 01010 adc0 adc0 200x 01011 adc1 adc0 200x 01100 adc2 adc2 10x 01101 adc3 adc2 10x 01110 adc2 adc2 200x 01111 adc3 adc2 200x 10000 adc0 adc1 1x 10001 adc1 adc1 1x 10010 n/a adc2 adc1 1x 10011 adc3 adc1 1x 10100 adc4 adc1 1x 10101 adc5 adc1 1x 10110 adc6 adc1 1x 10111 adc7 adc1 1x 11000 adc0 adc2 1x 11001 adc1 adc2 1x 11010 adc2 adc2 1x 11011 adc3 adc2 1x 11100 adc4 adc2 1x
221 atmega8535(l) 2502k?avr?10/06 adc control and status register a ? adcsra ? bit 7 ? aden: adc enable writing this bit to one enables the adc. by writing it to ze ro, the adc is turned off. turn- ing the adc off while a conversion is in progress, will terminate this conversion. ? bit 6 ? adsc: adc start conversion in single conversion mode, write this bit to one to start each conversion. in free run- ning mode, write this bit to one to start th e first conversion. the first conversion after adsc has been written after the adc has been enabled, or if adsc is written at the same time as the adc is enabled, will take 25 adc clock cycles instead of the normal 13. this first conversion performs initialization of the adc. adsc will read as one as long as a conversion is in progress. when the conversion is complete, it returns to zero. writing zero to this bit has no effect. ? bit 5 ? adate: adc auto trigger enable when this bit is written to on e, auto triggering of the ad c is enabled. the adc will start a conversion on a positive edge of the selected trigger signal. the trigger source is selected by setting the adc trigge r select bits, adts in sfior. ? bit 4 ? adif: adc interrupt flag this bit is set when an adc conversion completes and the data registers are updated. the adc conversion complete interrupt is executed if the adie bit and the i-bit in sreg are set. adif is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, adif is cleared by writing a logical one to the flag. beware that if doing a read-modify-write on adcsra, a pending interrupt can be dis- abled. this also applies if the sbi and cbi instructions are used. ? bit 3 ? adie: adc interrupt enable when this bit is written to one and the i-bit in sreg is set, the adc conversion com- plete interrupt is activated. ? bits 2:0 ? adps2:0: adc prescaler select bits these bits determine the division factor between the xtal frequency and the input clock to the adc. 11101 adc5 adc2 1x 11110 1.22v (v bg ) n/a 11111 0v (gnd) table 85. input channel and gain selections (continued) mux4..0 single ended input pos different ial input neg differential input gain bit 76543210 aden adsc adate adif adie adps2 adps1 adps0 adcsra read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
222 atmega8535(l) 2502k?avr?10/06 the adc data register ? adcl and adch adlar = 0 adlar = 1 when an adc conversion is complete, the result is found in these two registers. if differ- ential channels are used, the result is presented in two?s complement form. when adcl is read, the adc data register is not updated until adch is read. conse- quently, if the result is left adjusted and no mo re than 8-bit precision is required, it is sufficient to read adch. otherwise, adcl must be read first, then adch. the adlar bit in admux, and the muxn bits in admux affect the way the result is read from the registers. if adlar is set, the result is left adjusted. if adlar is cleared (default), the result is right adjusted. ? adc9:0: adc conversion result these bits represent the result from the conversion, as detailed in ?adc conversion result? on page 218. table 86. adc prescaler selections adps2 adps1 adps0 division factor 000 2 001 2 010 4 011 8 100 16 101 32 110 64 1 1 1 128 bit 151413121110 9 8 ? ? ? ? ? ? adc9 adc8 adch adc7 adc6 adc5 adc4 adc3 adc2 adc1 adc0 adcl 76543210 read/writerrrrrrrr rrrrrrrr initial value00000000 00000000 bit 151413121110 9 8 adc9 adc8 adc7 adc6 adc5 adc4 adc3 adc2 adch adc1 adc0 ? ????? adcl 76543210 read/writerrrrrrrr rrrrrrrr initial value00000000 00000000
223 atmega8535(l) 2502k?avr?10/06 special function io register ? sfior ? bit 7:5 ? adts2:0: adc auto trigger source if adate in adcsra is written to one, the value of these bits se lects which source will trigger an adc conversion. if adate is cleared, the adts2:0 settings will have no effect. a conversion will be triggered by the rising edge of the selected interrupt flag. note that switching from a trigger source that is cleared to a trigger source that is set, will generate a positive e dge on the trigger signal. if aden in adcsra is set, this will start a conversion. switching to free runn ing mode (adts[2:0]=0 ) will not cause a trig- ger event, even if the adc interrupt flag is set . ? bit 4 ? res: reserved bit this bit is reserved bit in the at mega8535, and will always read as zero. bit 76543210 adts2 adts1 adts0 ? acme pud psr2 psr10 sfior read/write r/w r/w r/w r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 87. adc auto trigger source selections adts2 adts1 adts0 trigger source 0 0 0 free running mode 0 0 1 analog comparator 0 1 0 external interrupt request 0 0 1 1 timer/counter0 compare match 1 0 0 timer/counter0 overflow 1 0 1 timer/counter1 compare match b 1 1 0 timer/counter1 overflow 1 1 1 timer/counter1 capture event
224 atmega8535(l) 2502k?avr?10/06 boot loader support ? read-while-write self-programming the boot loader support provides a real read-while-write self-programming mecha- nism for downloading and uploading program code by the mcu itself. this feature allows flexible application software updates controlled by the mc u using a flash-resi- dent boot loader program. the boot loader program can use any available data interface and associated protocol to read code and write (program) that code into the flash memory, or read the code from the program memory. the program code within the boot loader sectio n has the capability to write into the entire flash, including the boot loader memory. the boot loader can t hus even modify itself, and it can also erase itself from the code if the feature is not needed anymore. the size of the boot loader memory is configurable with fuses and the boot loader has two separate sets of boot lock bits which can be se t independently. this gives th e user a unique flexibility to select different levels of protection. boot loader features ? read-while-write self-programming ? flexible boot memory size ? high security (separate boot lock bits for a flexible protection) ? separate fuse to select reset vector ? optimized page (1) size ? code efficien t algorithm ? efficient read-mod ify-write support note: 1. a page is a section in the flash consisting of several bytes (see table 104 on page 241) used during programming. the page organization does not affect normal operation. application and boot loader flash sections the flash memory is organized in two main sections, the application section and the boot loader section (see figure 113). the size of the different sections is configured by the bootsz fuses as shown in table 93 on page 235 and figure 113. these two sec- tions can have different level of protection since they have different sets of lock bits. application section the application section is the section of the flash that is used for storing the application code. the protection level for the application section can be selected by the application boot lock bits (boot lock bits 0), see table 89 on page 227. the application section can never store any boot loader code since the spm instruction is disabled when exe- cuted from the application section. bls ? boot loader section while the application section is used for storing the application code, the the boot loader software must be located in the bls since the spm instruction can initiate a pro- gramming when executing from the bls only. the spm instruction can access the entire flash, including the bls itself. the protection level for the boot loader section can be selected by the boot loader lock bits (boot lock bits 1), see table 90 on page 227. read-while-write and no read-while-write flash sections whether the cpu supports read-while-write or if the cpu is halted during a boot loader software update is dependent on which address that is being programmed. in addition to the two sections that are conf igurable by the bootsz fuses as described above, the flash is also divided into two fixed sections, the read-while-write (rww) section and the no read-while-write (nrw w) section. the limit between the rww- and nrww sections is given in table 94 on page 235 and figure 113 on page 226. the main difference between the two sections is: ? when erasing or writing a page located inside the rww section, the nrww section can be read during the operation. ? when erasing or writing a page located in side the nrww section, the cpu is halted during the entire operation.
225 atmega8535(l) 2502k?avr?10/06 note that the user software can never read any code that is located inside the rww section during a boot loader software operation. the syntax ?read-while-write sec- tion? refers to which section that is being programmed (erased or written), not which section that actually is being read during a boot loader software update. rww ? read-while-write section if a boot loader software update is programming a page inside the rww section, it is possible to read code from the flash, but only code that is located in the nrww sec- tion. during an on-going programming, the software must ensure that the rww section never is being read. if the user software is trying to read code that is located inside the rww section (i.e., by a rcall/rjmp/lpm or an interrupt) during programming, the software might end up in an unknown state. to avoid this, the interrupts should either be disabled or moved to the boot loader section. the boot loader section is always located in the nrww section. the rww section busy bit (rwwsb) in the store program memory control register (spm cr) will be read as logical one as long as the rww section is blocked for reading. after a programming is completed, the rwwsb must be cleared by software before reading code located in the rww section. see ?store program memory control register ? spmcr? on page 228. for details on how to clear rwwsb. nrww ? no read-while-write section the code located in the nrww section can be read when the boot loader software is updating a page in the rww section. when the boot loader code updates the nrww section, the cpu is halted during the entire page erase or page write operation. figure 112. read-while-write vs. no read-while-write table 88. read-while-write features which section does the z- pointer address during the programming? which section can be read during programming? is the cpu halted? read-while- write supported? rww section nrww section no yes nrww section none yes no read-while-write (rww) section no read-while-write (nrww) section z-pointer addresses rww section z-pointer addresses nrww section cpu is halted during the operation code located in nrww section can be read during the operation
226 atmega8535(l) 2502k?avr?10/06 figure 113. memory sections (1) note: 1. the parameters in the figure above are given in table 93 on page 235. boot loader lock bits if no boot loader ca pability is needed, the entire flash is availabl e for application code. the boot loader has two separate sets of boot lock bits which can be set indepen- dently. this gives the user a unique flexibility to select different le vels of protection. the user can select: ? to protect the entire flash from a software update by the mcu. ? to protect only the boot loader flash section from a software update by the mcu. ? to protect only the application flash sect ion from a software update by the mcu. ? allow software update in the entire flash. see table 89 and table 90 for further details. the boot lock bits can be set in software and in serial or parallel programming mode, but they can be cleared by a chip erase command only. the general write lock (lock bit mode 2) does not control the program- ming of the flash memory by spm instruct ion. similarly, the general read/write lock (lock bit mode 1) does not control reading nor writing by lpm/spm, if it is attempted. $0000 flashend program memory bootsz = '11' application flash section boot loader flash section flashend program memory bootsz = '10' $0000 program memory bootsz = '01' program memory bootsz = '00' application flash section boot loader flash section $0000 flashend application flash section flashend end rww start nrww application flash section boot loader flash section boot loader flash section end rww start nrww end rww start nrww $0000 end rww, end application start nrww, start boot loader application flash section application flash section application flash section read-while-write section no read-while-write section read-while-write section no read-while-write section read-while-write section no read-while-write section read-while-write section no read-while-write section end application start boot loader end application start boot loader end application start boot loader
227 atmega8535(l) 2502k?avr?10/06 note: 1. ?1? means unprogrammed, ?0? means programmed . note: 1. ?1? means unprogrammed, ?0? means programmed. entering the boot loader program entering the boot loader takes place by a jump or call from the application program. this may be initiated by a trigger such as a command received via usart, or spi inter- face. alternatively, the boot reset fuse can be programmed so that the reset vector is pointing to the boot flash start address after a reset. in this case, the boot loader is started after a reset. after the application code is loaded, the program can start execut- ing the application code. note that the fuses cannot be changed by the mcu itself. this means that once the boot reset fuse is programmed, the reset vector will always point to the boot loader reset and the fuse can only be changed through the serial or parallel programming interface. note: 1. ?1? means unprogrammed, ?0? means programmed. table 89. boot lock bit0 protection modes (application section) (1) blb0 mode blb02 blb01 protection 111 no restrictions for spm or lpm accessing the application section. 2 1 0 spm is not allowed to write to the application section. 300 spm is not allowed to write to the application section, and lpm executing from the boot loader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. 401 lpm executing from the boot loader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. table 90. boot lock bit1 protection modes (boot loader section) (1) blb1 mode blb12 blb11 protection 111 no restrictions for spm or lpm accessing the boot loader section. 2 1 0 spm is not allowed to write to the boot loader section. 300 spm is not allowed to write to the boot loader section, and lpm executing from the application section is not allowed to read from the boot loader section. if interrupt vectors are placed in the appl ication section, interrupts are disabled while executing from the boot loader section. 401 lpm executing from the application section is not allowed to read from the boot loader section. if interrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section. table 91. boot reset fuse (1) bootrst reset address 1 reset vector = application reset (address 0x0000) 0 reset vector = boot loader reset (see table 93 on page 235)
228 atmega8535(l) 2502k?avr?10/06 store program memory control register ? spmcr the store program memory control register contains the control bits needed to control the boot loader operations. ? bit 7 ? spmie: spm interrupt enable when the spmie bit is written to one, and the i-bit in the status register is set (one), the spm ready interrupt will be enabled. the sp m ready interrupt will be executed as long as the spmen bit in the spmcr register is cleared. ? bit 6 ? rwwsb: read-while-write section busy when a self-programming (page erase or page write) operation to the rww section is initiated, the rwwsb will be set (one) by hardware. when the rwwsb bit is set, the rww section cannot be accessed. the rwws b bit will be cleared if the rwwsre bit is written to one after a self-programming operation is completed. alternatively the rwwsb bit will automatically be cleared if a page load operat ion is initiated. ? bit 5 ? res: reserved bit this bit is a reserved bit in the atmega8535 and always read as zero. ? bit 4 ? rwwsre: read-while-write section read enable when programming (page erase or page write) to the rww section, the rww section is blocked for reading (the rwwsb will be set by hardware). to re-enable the rww section, the user software must wait until th e programming is co mpleted (spmen will be cleared). then, if the rwwsre bit is writt en to one at the same time as spmen, the next spm instruction within four clock cy cles re-enables the rww section. the rww section cannot be re-enabled while the flash is busy with a page erase or a page write (spmen is set). if the rwwsre bit is writt en while the flash is being loaded, the flash load operation will abort and th e data loaded will be lost. ? bit 3 ? blbset: boot lock bit set if this bit is written to one at the same time as spmen, the next spm instruction within four clock cycles sets boot lock bits, acco rding to the data in r0. the data in r1 and the address in the z-pointer are ignored. the blbset bit will automatically be cleared upon completion of the lock bit set, or if no spm instruction is executed within four clock cycles. an lpm instruction within th ree cycles after blbset and spmen are set in the spmcr register, will read either the lock bits or th e fuse bits (dependi ng on z0 in the z- pointer) into the destination register. see ?reading the fuse and lock bits from soft- ware? on page 232 for details. ? bit 2 ? pgwrt: page write if this bit is written to one at the same time as spmen, the next spm instruction within four clock cycles execut es page write, with the data stor ed in the temporary buffer. the page address is taken from the high part of the z-pointer. the data in r1 and r0 are ignored. the pgwrt bit will auto-c lear upon completion of a page write, or if no spm instruction is executed within four clock c ycles. the cpu is halted during the entire page write operation if the nrww section is addressed. ? bit 1 ? pgers: page erase if this bit is written to one at the same time as spmen, the next spm instruction within four clock cycles executes page erase. the page address is taken from the high part of bit 765 4 3210 spmie rwwsb ? rwwsre blbset pgwrt pgers spmen spmcr read/write r/w r r r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
229 atmega8535(l) 2502k?avr?10/06 the z-pointer. the data in r1 and r0 are ignored. the pg ers bit will auto-clear upon completion of a page erase, or if no spm instruction is executed within four clock cycles. the cpu is halted during the entire page write operation if the nrww section is addressed. ? bit 0 ? spmen: store program memory enable this bit enables the spm instruction for the next four clock cycles. if written to one together with either rwwsre, blbset, pgwrt? or pgers, the following spm instruction will have a special meaning, see description above. if only spmen is written, the following spm instruction will store the va lue in r1:r0 in the temporary page buffer addressed by the z-pointer. the lsb of the z-pointer is ignored. the spmen bit will auto-clear upon completion of an spm instruction, or if no spm instruction is executed within four clock cycles. during page erase and page write, the spmen bit remains high until the operation is completed. writing any other combination than ?10001?, ?01001?, ?00101?, ?00011? or ?00001? in the lower five bits will have no effect. addressing the flash during self- programming the z-pointer is used to address the spm commands. since the flash is organized in pages (see table 104 on page 241), the program counter can be treated as having two different sections. one section, consisting of the least significant bits, is addressing the wo rds within a page, while the most significant bits are addressing the pages. this is shown in figure 114. note that the page erase and page write operations are addressed independently. therefore it is of major impor- tance that the boot loader software addresses the same page in both the page erase and page write operation. once a programming operation is initiated, the address is latched and the z-pointer can be used for other operations. the only spm operation that does not use the z-pointer is setting the boot loader lock bits. the content of the z-pointer is ignored and will have no effect on the operation. the lpm instruction does also use the z-pointer to store the address. since this instruction addresses the flash byte by byte, also th e lsb (bit z0) of the z-pointer is used. bit 151413121110 9 8 zh (r31) z15 z14 z13 z12 z11 z10 z9 z8 zl (r30) z7z6z5z4z3z2z1z0 76543210
230 atmega8535(l) 2502k?avr?10/06 figure 114. addressing the flash during spm (1) notes: 1. the different variables used+ in figure 114 are listed in table 95 on page 236. 2. pcpage and pcword are listed in table 104 on page 241. self-programming the flash the program memory is updated in a page by page fashion. before programming a page with the data stored in the temporary page buffer, the page must be erased. the temporary page buffer is filled one word at a time using spm and the buffer can be filled either before the page erase command or between a page erase and a page write operation: alternative 1, fill the bu ffer before a page erase: ? fill temporary page buffer ? perform a page erase ? perform a page write alternative 2, fill the bu ffer after page erase: ? perform a page erase ? fill temporary page buffer ? perform a page write if only a part of the page needs to be changed, the rest of the page must be stored (for example in the temporary page buffer) before the erase, and then be rewritten. when using alternative 1, the boot loader provi des an effective read-modify-write feature which allows the user software to first read the page, do the necessary changes, and then write back the modified data. if alternativ e 2 is used, it is not possible to read the old data while loading since the page is already erased. the temporary page buffer can be accessed in a random sequence. it is essential that the page address used in both the page erase and page write operation is addressing the same page. see ?simple assembly code example for a boot loader? on page 233 for an assembly code example. program memory 0 1 15 z - register bit 0 zpagemsb word address within a page page address within the flash zpcmsb instruction word pag e pcword[pagemsb:0]: 00 01 02 pageend pag e pcword pcpage pcmsb pagemsb program counter
231 atmega8535(l) 2502k?avr?10/06 performing page erase by spm to execute page erase, set up the address in the z-pointer, write ?x0000011? to spmcr and execute spm within four clock cycles after writing spmcr. the data in r1 and r0 is ignored. the page address must be written to pcpage in the z-register. other bits in the z-pointer will be ignored during this operation. ? page erase to the rww section: the nrww section can be read during the page erase. ? page erase to the nrww section: the cpu is halted during the operation. filling the temporary buffer (page loading) to write an instruction word, set up the addre ss in the z-pointer and data in r1:r0, write ?00000001? to spmcr and execute spm within four clock cycles after writing spmcr. the content of pcword in the z-register is used to address the data in the temporary buffer. the temporary buffer will auto-erase after a page write operation or by writing the rwwsre bit in spmcr. it is also erased after a system reset. note that it is not possible to write more than one time to each address without erasing the temporary buffer. note: if the eeprom is written in the middle of an spm page load operation, all data loaded will be lost. performing a page write to execute page write, set up the address in the z-pointer, write ?x0000101? to spmcr and execute spm within four clock cycles after writing spmcr. the data in r1 and r0 is ignored. the page address must be written to pcpage. other bits in the z- pointer must be written to zero during this operation. ? page write to the rww section: the nrww section can be read during the page write. ? page write to the nrww section: the cpu is halted during the operation. using the spm interrupt if the spm interrupt is enabled, the spm interrupt will generate a constant interrupt when the spmen bit in spmcr is cleared. th is means that the interrupt can be used instead of polling the spmcr register in software. when using the spm interrupt, the interrupt vectors should be moved to the bls section to avoid that an interrupt is accessing the rww section when it is blocked for reading. how to move the interrupts is described in ?interrupts? on page 46. consideration while updating bls special care must be taken if the user allows the boot loader section to be updated by leaving boot lock bit 11 unprogrammed. an accidental write to the boot loader itself can corrupt the entire boot loader, and further software updates might be impossible. if it is not necessary to change the boot loader software itself, it is recommended to pro- gram the boot lock bit 11 to protect the boot loader software from any internal software changes. prevent reading the rww section during self-programming during self-programming (either page erase or page write), the rww section is always blocked for reading. the user software itself must prevent that this section is addressed during the self-programming operation. the rwwsb in the spmcr will be set as long as the rww section is busy. during self-programming the interrupt vector table should be moved to the bls as described in ?interrupts? on page 46, or the inter- rupts must be disabled. before addressing the rww section after the programming is completed, the user software must clear the rwwsb by writing the rwwsre. see ?simple assembly code example for a bo ot loader? on page 233 for an example.
232 atmega8535(l) 2502k?avr?10/06 setting the boot loader lock bits by spm to set the boot loader lock bits, write the desired data to r0, write ?x0001001? to spmcr and execute spm within four clock cycles after writing spmcr. the only accessible lock bits are t he boot lock bits that may prevent the application and boot loader section from any software update by the mcu. see table 89 and table 90 for how the different settings of the boot loader bits affect the flash access. if bits 5..2 in r0 are clea red (zero), the corresponding bo ot lock bit will be programmed if an spm instruction is ex ecuted within four cycles after blbset and spmen are set in spmcr. the z-pointer is don?t ca re during this operat ion, but for future compatibility it is recommended to load the z-pointer with 0x0001 (same as used for reading the lock bits). for future compatibility it is also recommended to set bits 7, 6, 1, and 0 in r0 to ?1? when writing the lock bits. when programming the lock bits the entire flash can be read during the operation. eeprom write prevents writing to spmcr note that an eeprom write operation will block all software programming to flash. reading the fuses and lock bits from software will al so be prevented during the eeprom write operation. it is recommended that the user ch ecks the status bit (eewe) in the eecr register and verifies that the bit is cleared before writing to the spmcr register. reading the fuse and lock bits from software it is possible to read both the fuse and lock bits from software. to read the lock bits, load the z-pointer with 0x00 01 and set the blbset and spmen bits in spmcr. when an lpm instruction is executed within thre e cpu cycles after the blbset and spmen bits are set in spmcr, the value of the lock bits will be loaded in the destination regis- ter. the blbset and spmen bits will auto-cle ar upon completion of reading the lock bits or if no lpm instruction is executed wit hin three cpu cycles or no spm instruction is executed within four cpu cycles. when blbset and spmen are cleared, lpm will work as described in the instruction set manual. the algorithm for reading the fuse low bits is similar to the one described above for reading the lock bits. to read the fuse low bits, load the z-pointer with 0x0000 and set the blbset and spmen bits in spmcr. when an lpm instru ction is executed within three cycles after the blbset and spmen bits are set in the spmcr, the value of the fuse low bits (flb) will be loaded in the des tination register as shown below. refer to table 99 on page 239 for a detailed description and mapping of the fuse low bits. similarly, when reading the fuse high bits, load 0x0003 in the z-pointer. when an lpm instruction is executed within three cycles after the blbset and spmen bits are set in the spmcr, the value of the fuse high bits (fhb) will be loaded in the destin ation reg- ister as shown below. refer to table 98 on page 238 for detailed description and mapping of the fuse high bits. bit 76543210 r0 1 1 blb12 blb11 blb02 blb01 1 1 bit 76543210 rd ? ? blb12 blb11 blb02 blb01 lb2 lb1 bit 76543210 rd flb7 flb6 flb5 flb4 flb3 flb2 flb1 flb0 bit 76543210 rd fhb7 fhb6 fhb5 fhb4 fhb3 fhb2 fhb1 fhb0
233 atmega8535(l) 2502k?avr?10/06 fuse and lock bits that are programmed, will be read as zero. fuse and lock bits that are unprogrammed, will be read as one. preventing flash corruption during periods of low v cc, the flash program can be corrupted because the supply volt- age is too low for the cpu and the flash to operate properly. these issues are the same as for board level systems using the flash, and the same design solutions should be applied. a flash program corruption can be caused by two situations when the voltage is too low. first, a regular write sequence to the flash requires a minimum voltage to operate cor- rectly. secondly, the cpu itself can execute in structions incorrectly, if the supply voltage for executing instructions is too low. flash corruption can easily be avoided by following these design recommendations (one is sufficient): 1. if there is no need for a boot loader update in the system, program the boot loader lock bits to prevent any boot loader software updates. 2. keep the avr reset active (low) duri ng periods of insufficient power supply voltage. this can be done by enabling the internal brown-out detector (bod) if the operating voltage matches the detection level. if not, an external low v cc reset protection circuit can be used. if a reset occurs while a write operation is in progress, the write operation will be co mpleted provided th at the power supply voltage is sufficient. 3. keep the avr core in power-down sleep mode during periods of low v cc . this will prevent the cpu from attempting to decode and execute instructions, effec- tively protecting the spmcr register and thus the flash from unintentional writes. programming time for flash when using spm the calibrated rc oscilla tor is used to time flash accesses. table 92 shows the typical programming time for flash accesses from the cpu. simple assembly code example for a boot loader ;-the routine writes one page of data from ram to flash ; the first data location in ra m is pointed to by the y pointer ; the first data locati on in flash is pointed to by the z pointer ;-error handling is not included ;-the routine must be plac ed inside the boot space ; (at least the do_spm sub routine). only code inside nrww section can ; be read during self-programming (page erase and page write). ;-registers used: r0, r1, temp1 (r16), temp2 (r17), looplo (r24), ; loophi (r25), spmcrval (r20) ; storing and restoring of register s is not included in the routine ; register usage can be optimiz ed at the expense of code size ;-it is assumed that either the in terrupt table is moved to the boot ; loader section or that the interrupts are disabled. .equ pagesizeb = pagesize*2 ;pagesizeb is page size in bytes, not words .org smallbootstart write_page: ; page erase ldi spmcrval, (1< 234 atmega8535(l) 2502k?avr?10/06 ; re-enable the rww section ldi spmcrval, (1< 235 atmega8535(l) 2502k?avr?10/06 in temp2, sreg cli ; check that no eeprom write access is present wait_ee: sbic eecr, eewe rjmp wait_ee ; spm timed sequence out spmcr, spmcrval spm ; restore sreg (to enable interrupts if originally enabled) out sreg, temp2 ret atmega8535 boot loader parameters in table 93 through table 95, the parameters used in the description of the self pro- gramming are given. note: 1. the different bootsz fuse conf igurations are shown in figure 113 note: 1. for details about these two section, see ?nrww ? no read-while-write section? on page 225 and ?rww ? read-while-write section? on page 225 table 93. boot size configuration (1) boots z1 boots z0 boot size pages appli- cation flash section boot loader flash section end appli- cation section boot reset address (start boot loader section) 11 128 words 4 0x000 - 0xf7f 0xf80 - 0xfff 0xf7f 0xf80 10 256 words 8 0x000 - 0xeff 0xf00 - 0xfff 0xeff 0xf00 01 512 words 16 0x000 - 0xdff 0xe00 - 0xfff 0xdff 0xe00 00 1024 words 32 0x000 - 0xbff 0xc00 - 0xfff 0xbff 0xc00 table 94. read-while-write limit (1) section pages address read-while-write secti on (rww) 96 0x000 - 0xbff no read-while-write section (nrww) 32 0xc00 - 0xfff
236 atmega8535(l) 2502k?avr?10/06 note: 1. z15:z13: always ignored z0: should be zero for all spm commands, byte select for the lpm instruction. see ?addressing the flash during self-pro gramming? on page 229 for details about the use of z-pointer during self-programming. table 95. explanation of different variables used in figure 114 and the mapping to the z-pointer (1) variable corresponding z-value description pcmsb 11 most significant bit in the program counter. (the program counter is 12 bits pc[11:0]) pag e m s b 4 most significant bit which is used to address the words within one page (64 words in a page requires five bits pc [4:0]). zpcmsb z12 bit in z-register that is mapped to pcmsb. because z0 is not used, the zpcmsb equals pcmsb + 1. zpagemsb z5 bit in z-register that is mapped to pcmsb. because z0 is not used, the zpagemsb equals pagemsb + 1. pcpage pc[11:5] z12:z6 program counter page address: page select, for page erase and page write pcword pc[4:0] z5:z1 program counter word address: word select, for filling temporary buffer (must be zero during page write operation)
237 atmega8535(l) 2502k?avr?10/06 memory programming program and data memory lock bits the atmega8535 provides six lock bits which can be left unprogrammed (?1?) or can be programmed (?0?) to obtain the additional features listed in table 97. the lock bits can only be erased to ?1? with the chip erase command. note: 1. ?1? means unprogrammed, ?0? means programmed table 96. lock bit byte (1) lock bit byte bit no description default value 7 ? 1 (unprogrammed) 6 ? 1 (unprogrammed) blb12 5 boot lock bit 1 (unprogrammed) blb11 4 boot lock bit 1 (unprogrammed) blb02 3 boot lock bit 1 (unprogrammed) blb01 2 boot lock bit 1 (unprogrammed) lb2 1 lock bit 1 (unprogrammed) lb1 0 lock bit 1 (unprogrammed) table 97. lock bit protection modes (2) memory lock bits protection type lb mode lb2 lb1 1 1 1 no memory lock features enabled. 210 further programming of the flash and eeprom is disabled in parallel and serial programming mode. the fuse bits are locked in both serial and parallel programming mode. (1) 300 further programming and verification of the flash and eeprom is disabled in parall el and serial programming mode. the fuse bits are locked in both serial and parallel programming mode. (1) blb0 mode blb02 blb01 111 no restrictions for spm or lpm accessing the application section. 2 1 0 spm is not allowed to write to the application section. 300 spm is not allowed to write to the application section, and lpm executing from the boot loader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. 401 lpm executing from the boot loader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. blb1 mode blb12 blb11
238 atmega8535(l) 2502k?avr?10/06 notes: 1. program the fuse bits before programming the lock bits. 2. ?1? means unprogrammed, ?0? means programmed. fuse bits the atmega8535 has two fuse bytes. table 98 and table 99 describe briefly the func- tionality of all the fuses and how they are mapped into the fuse bytes. note that the fuses are read as logical zero, ?0?, if they are programmed. notes: 1. the spien fuse is not accessible in serial programming mode. 2. the ckopt fuse functionality depends on the setting of the cksel bits. see ?clock sources? on page 25. for details. 3. the default value of bootsz1..0 result s in maximum boot size. see table 93 on page 235. 111 no restrictions for spm or lpm accessing the boot loader section. 2 1 0 spm is not allowed to write to the boot loader section. 300 spm is not allowed to write to the boot loader section, and lpm executing from the application section is not allowed to read from the boot loader section. if interrupt vectors are placed in the appl ication section, interrupts are disabled while executing from the boot loader section. 401 lpm executing from the application section is not allowed to read from the boot loader section. if interrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section. table 97. lock bit protection modes (2) (continued) memory lock bits protection type table 98. fuse high byte fuse high byte bit no description default value s8535c 7 select at90s8535 compatibility mode 1 (unprogrammed) wdton 6 wdt always on 1 (unprogrammed, wdt enabled by wdtcr) spien (1) 5 enable serial program and data downloading 0 (programmed, spi prog. enabled) ckopt (2) 4 oscillator options 1 (unprogrammed) eesave 3 eeprom memory is preserved through the chip erase 1 (unprogrammed, eeprom not preserved) bootsz1 2 select boot size (see table 93 for details) 0 (programmed) (3) bootsz0 1 select boot size (see table 93 for details) 0 (programmed) (3) bootrst 0 select reset vector 1 (unprogrammed)
239 atmega8535(l) 2502k?avr?10/06 notes: 1. the default value of sut1..0 results in maximum start-up time. see table 10 on page 30 for details. 2. the default setting of cksel3..0 result s in internal rc oscillator @ 1 mhz. see table 2 on page 25 for details. the status of the fuse bits is not affected by chip erase. note that the fuse bits are locked if lock bit 1 (lb1) is programmed. program the fuse bits before programming the lock bits. latching of fuses the fuse values are latched when the device enters programming mode and changes of the fuse values will have no effect until the part leaves programming mode. this does not apply to the eesave fuse which will take effect once it is programmed. the fuses are also latched on power-up in normal mode. signature bytes all atmel microcontrollers have a three-byte signature code which identifies the device. this code can be read in both serial and parallel mode, also when the device is locked. the three bytes reside in a separate address space. for the atmega8535 the signature bytes are: 1. 0x000: 0x1e (indicates manufactured by atmel) 2. 0x001: 0x93 (indicates 8 kb flash memory) 3. 0x002: 0x08 (indicates atmega8535 device when 0x001 is 0x93) calibration byte the atmega8535 stores four different calibration values for the internal rc oscillator. these bytes resides in the signature row high byte of the addresses 0x000, 0x0001, 0x0002, and 0x0003 for 1, 2, 4, and 8 mhz respectively. during reset, the 1 mhz value is automatically loaded into the osccal register. if other frequencies are used, the calibration value has to be loaded manually, see ?o scillator calibration register ? osc- cal? on page 30 for details. table 99. fuse low byte fuse low byte bit no description default value bodlevel 7 brown out detector trigger level 1 (unprogrammed) boden 6 brown out detector enable 1 (unprogrammed, bod disabled) sut1 5 select start-up time 1 (unprogrammed) (1) sut0 4 select start-up time 0 (programmed) (1) cksel3 3 select clock source 0 (programmed) (2) cksel2 2 select clock source 0 (programmed) (2) cksel1 1 select clock source 0 (programmed) (2) cksel0 0 select clock source 1 (unprogrammed) (2)
240 atmega8535(l) 2502k?avr?10/06 parallel programming parameters, pin mapping, and commands this section describes how to parallel program and verify flash program memory, eeprom data memory, memory lock bits, and fuse bits in the atmega8535. pulses are assumed to be at least 250 ns unless otherwise noted. signal names in this section, some pins of the atmega8535 are referenced by signal names describ- ing their functionality during parallel programming, see figure 115 and table 100. pins not described in the following table are referenced by pin names. the xa1/xa0 pins determine the action executed when the xtal1 pin is given a posi- tive pulse. the bit coding is shown in table 102. when pulsing wr or oe , the command loaded determines the action executed. the dif- ferent commands are shown in table 103. figure 115. parallel programming table 100. pin name mapping signal name in programming mode pin name i/o function rdy/bsy pd1 o 0: device is busy programming, 1: device is ready for new command oe pd2 i output enable (active low) wr pd3 i write pulse (active low) bs1 pd4 i byte select 1 (?0? selects low byte, ?1? selects high byte) xa0 pd5 i xtal action bit 0 xa1 pd6 i xtal action bit 1 pagel pd7 i program memory and eeprom data page load bs2 pa0 i byte select 2 (?0? selects low byte, ?1? selects 2?nd high byte) data pb7 - 0 i/o bi-directional data bus (output when oe is low) vcc +5v gnd xtal1 pd1 pd2 pd3 pd4 pd5 pd6 pb7 - pb0 data reset pd7 +12 v bs1 xa0 xa1 oe rdy/bsy pagel pa0 wr bs2 avcc
241 atmega8535(l) 2502k?avr?10/06 table 101. pin values used to enter programming mode pin symbol value pagel prog_enable[3] 0 xa1 prog_enable[2] 0 xa0 prog_enable[1] 0 bs1 prog_enable[0] 0 table 102. xa1 and xa0 coding xa1 xa0 action when xtal1 is pulsed 0 0 load flash or eeprom address (high or low address byte determined by bs1) 0 1 load data (high or low data byte for flash determined by bs1) 1 0 load command 1 1 no action, idle table 103. command byte bit coding command byte command executed 1000 0000 chip erase 0100 0000 write fuse bits 0010 0000 write lock bits 0001 0000 write flash 0001 0001 write eeprom 0000 1000 read signature bytes and calibration byte 0000 0100 read fuse and lock bits 0000 0010 read flash 0000 0011 read eeprom table 104. no. of words in a page and no. of pages in the flash flash size page size pcword no. of pages pcpage pcmsb 4k words (8k bytes) 32 words pc[4:0] 128 pc[11:5] 11 table 105. no. of words in a page and no. of pages in the eeprom eeprom size page size pcword no. of pages pcpage eeamsb 512 bytes 4 bytes eea[1:0] 128 eea[8:2] 8
242 atmega8535(l) 2502k?avr?10/06 parallel programming enter programming mode the following algorithm puts the devi ce in parallel programming mode: 1. apply 4.5 - 5.5v between v cc and gnd, and wait at least 100 s. 2. set reset to ?0? and toggle xtal1 at least six times. 3. set the prog_enable pins listed in table 101 on page 241 to ?0000? and wait at least 100 ns. 4. apply 11.5 - 12.5v to reset . any activity on prog_enable pins within 100 ns after +12v has been applied to reset , will cause the device to fail entering pro- gramming mode. note, if external crystal or external rc configuration is selected, it may not be possible to apply qualified xtal1 pulses. in such cases, the following algorithm should be followed: 1. set prog_enable pins listed in table 101 on page 241 to ?0000?. 2. apply 4.5 - 5.5v between v cc and gnd simultaneously as 11.5 - 12.5v is applied to reset . 3. wait 100 ns. 4. re-program the fuses to ensure that external clock is selected as clock source (cksel3:0 = 0b0000) if lock bits are programmed, a chip erase command must be executed before changing the fuses. 5. exit programming mode by power the device down or by bringing reset pin to 0b0. 6. entering programming mode with the original algorithm, as described above. considerations for efficient programming the loaded command and address are retained in the device during programming. for efficient programming, the following should be considered. ? the command needs only be loaded once when writing or reading multiple memory locations. ? skip writing the data value 0xff, that is the contents of the entire eeprom (unless the eesave fuse is programmed) and flash after a chip erase. ? address high byte needs only be loaded before programming or reading a new 256 word window in flash or 256 byte eeprom . this consideration also applies to signature bytes reading. chip erase the chip erase will er ase the flash and eeprom (1) memories plus lock bits. the lock bits are not reset until the program memory has been completely erased. the fuse bits are not changed. a chip erase must be performed before the flash and/or the eeprom is reprogrammed. note: 1. the eeprpom memory is preserved du ring chip erase if the eesave fuse is programmed. load command ?chip erase? 1. set xa1, xa0 to ?10?. this enables command loading. 2. set bs1 to ?0?. 3. set data to ?1000 0000?. this is the command for chip erase. 4. give xtal1 a positive pulse. this loads the command. 5. give wr a negative pulse. this starts the chip erase. rdy/bsy goes low. 6. wait until rdy/bsy goes high before loading a new command.
243 atmega8535(l) 2502k?avr?10/06 programming the flash the flash is organized in pages, see table 104 on page 241. when programming the flash, the program data is latched into a page buffer. this allows one page of program data to be programmed simultaneously. the following procedure describes how to pro- gram the entire flash memory: a. load command ?write flash? 1. set xa1, xa0 to ?10?. this enables command loading. 2. set bs1 to ?0?. 3. set data to ?0001 0000?. this is the command for write flash. 4. give xtal1 a positive pulse. this loads the command. b. load address low byte 1. set xa1, xa0 to ?00?. this enables address loading. 2. set bs1 to ?0?. this selects low address. 3. set data = address low byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the address low byte. c. load data low byte 1. set xa1, xa0 to ?01?. this enables data loading. 2. set data = data low byte (0x00 - 0xff). 3. give xtal1 a positive pulse. this loads the data byte. d. load data high byte 1. set bs1 to ?1?. this selects high data byte. 2. set xa1, xa0 to ?01?. this enables data loading. 3. set data = data high byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the data byte. e. latch data 1. set bs1 to ?1?. this selects high data byte. 2. give pagel a positive pulse. this latches the data bytes. (see figure 117 for signal waveforms.) f. repeat b through e until the entire buffer is filled or until all data within the page is loaded. while the lower bits in the address are mapped to words within the page, the higher bits address the pages with in the flash. this is illustrated in figure 116 on page 244. note that if less than eight bits are required to address words in the page (pagesize < 256), the most significant bit(s) in the address low byte are used to address the page when performing a page write. g. load address high byte 1. set xa1, xa0 to ?00?. this enables address loading. 2. set bs1 to ?1?. this selects high address. 3. set data = address high byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the address high byte. h. program page 1. set bs1 to ?0?. 2. give wr a negative pulse. this starts programming of the entire page of data. rdy/bsy goes low.
244 atmega8535(l) 2502k?avr?10/06 3. wait until rdy/bsy goes high. (see figure 117 for signal waveforms) i. repeat b through h until the entire flash is programmed or until all data has been programmed. j. end page programming 1. 1. set xa1, xa0 to ?10?. this enables command loading. 2. set data to ?0000 0000?. this is the command for no operation. 3. give xtal1 a positive pulse. this loads the command, and the internal write sig- nals are reset. figure 116. addressing the flash which is organized in pages (1) note: 1. pcpage and pcword are listed in table 104 on page 241 . figure 117. programming the flash waveforms (1) note: 1. ?xx? is don?t care. the letters re fer to the programming description above. program memory word address within a page page address within the flash instruction word pag e pcword[pagemsb:0]: 00 01 02 pageend pag e pcword pcpage pcmsb pagemsb program counter rdy/bsy wr oe reset +12v pagel bs2 0x10 addr. low addr. high data data low data high addr. low data low data high xa1 xa0 bs1 xtal1 xx xx xx abcdebcdegh f
245 atmega8535(l) 2502k?avr?10/06 programming the eeprom the eeprom is organized in pages, see table 105 on page 241. when programming the eeprom, the program data is latched into a page buffer . this allows one page of data to be programmed simultaneously. the programming algorithm for the eeprom data memory is as follows (refer to ?programming the flash? on page 243 for details on command, address and data loading): 1. a: load command ?0001 0001?. 2. g: load address high byte (0x00 - 0xff). 3. b: load address low byte (0x00 - 0xff). 4. c: load data (0x00 - 0xff). 5. e: latch data (give pagel a positive pulse). k: repeat 3 through 5 until the entire buffer is filled. l: program eeprom page. 1. set bs1 to ?0?. 2. give wr a negative pulse. this starts programming of the eeprom page. rdy/bsy goes low. 3. wait until to rdy/bsy goes high before programming the next page. (see figure 118 for signal waveforms.) figure 118. programming the eeprom waveforms reading the flash the algorithm for reading the flash memory is as follows (refer to ?programming the flash? on page 243 for details on command and address loading): 1. a: load command ?0000 0010?. 2. g: load address high byte (0x00 - 0xff). 3. b: load address low byte (0x00 - 0xff). 4. set oe to ?0?, and bs1 to ?0?. the flash word low byte can now be read at data. 5. set bs1 to ?1?. the flash word high byte can now be read at data. 6. set oe to ?1?. rdy/bsy wr oe reset +12v pagel bs2 0x11 addr. high data addr. low data addr. low data xx xa1 xa0 bs1 xtal1 xx agbceb c el k
246 atmega8535(l) 2502k?avr?10/06 reading the eeprom the algorithm for readi ng the eeprom memory is as follows (refer to ?programming the flash? on page 243 for details on command and address loading): 1. a: load command ?0000 0011?. 2. g: load address high byte (0x00 - 0xff). 3. b: load address low byte (0x00 - 0xff). 4. set oe to ?0?, and bs1 to ?0?. the eeprom data byte can now be read at data. 5. set oe to ?1?. programming the fuse low bits the algorithm for programming the fuse low bits is as follows (refer to ?programming the flash? on page 243 for details on command and data loading): 1. a: load command ?0100 0000?. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. set bs1 to ?0? and bs2 to ?0?. this selects low data byte. 4. give wr a negative pulse and wait for rdy/bsy to go high. programming the fuse high bits the algorithm for programming the fuse high bits is as follows (refer to ?programming the flash? on page 243 for details on command and data loading): 1. a: load command ?0100 0000?. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. set bs1 to ?1? and bs2 to ?0?. this selects high data byte. 4. give wr a negative pulse and wait for rdy/bsy to go high. 5. set bs1 to ?0?. this selects low data byte. figure 119. programming the fuses waveforms rdy/bsy wr oe reset +12v pagel bs2 $40 data data xx xa1 xa0 bs1 xtal1 ac $40 data xx ac write fuse low byte write fuse high byte
247 atmega8535(l) 2502k?avr?10/06 programming the lock bits the algorithm for programming the lock bits is as follows (refer to ?programming the flash? on page 243 for details on command and data loading): 1. a: load command ?0010 0000?. 2. c: load data low byte. bit n = ?0? programs the lock bit. 3. give wr a negative pulse and wait for rdy/bsy to go high. the lock bits can only be cleared by executing chip erase. reading the fuse and lock bits the algorithm for reading the fuse and lock bits is as follows (refer to ?programming the flash? on page 243 for details on command loading): 1. a: load command ?0000 0100?. 2. set oe to ?0?, bs2 to ?0?, and bs1 to ?0?. the status of the fuse low bits can now be read at data (?0? means programmed). 3. set oe to ?0?, bs2 to ?1?, and bs1 to ?1?. the status of the fuse high bits can now be read at data (?0? means programmed). 4. set oe to ?0?, bs2 to ?0?, and bs1 to ?1?. the status of the lock bits can now be read at data (?0? means programmed). 5. set oe to ?1?. figure 120. mapping between bs1, bs2 and the fuse- and lock bits during read reading the signature bytes the algorithm for reading the signature bytes is as follows (refer to ?programming the flash? on page 243 for details on command and address loading): 1. a: load command ?0000 1000?. 2. b: load address low byte (0x00 - 0x02). 3. set oe to ?0?, and bs to ?0?. the selected signature byte can now be read at data. 4. set oe to ?1?. reading the calibration byte the algorithm for reading the calibration byte is as follows (refer to ?programming the flash? on page 243 for details on command and address loading): 1. a: load command ?0000 1000?. 2. b: load address low byte, 0x00. 3. set oe to ?0?, and bs1 to ?1?. the calibration byte can now be read at data. 4. set oe to ?1?. lock bits 0 1 bs2 fuse high byte bs1 data fuse low byte 0 1
248 atmega8535(l) 2502k?avr?10/06 parallel programming characteristics figure 121. parallel programming timing, including some general timing requirements figure 122. parallel programming timing, loading sequence with timing requirements (1) note: 1. the timing requirements shown in figure 121 (i.e. t dvxh , t xhxl , and t xldx ) also apply to loading operation. data & contol (data, xa0/1, bs1, bs2) xtal1 t xhxl t wlwh t dvxh t xldx t plwl t wlrh wr rdy/bsy pagel t phpl t plbx t bvph t xlwl t wlbx t bvwl wlrl xtal1 pagel t plxh xlxh t t xlph addr0 (low byte) data (low byte) data (high byte) addr1 (low byte) data bs1 xa0 xa1 load address (low byte) load data (low byte) load data (high byte) load data load address (low byte)
249 atmega8535(l) 2502k?avr?10/06 figure 123. parallel programming timing, readi ng sequence (within the same page) with timing requirements (1) note: 1. the timing requirements shown in figure 121 (i.e. t dvxh , t xhxl , and t xldx ) also apply to reading operation. xtal1 oe addr0 (low byte) data (low byte) data (high byte) addr1 (low byte) data bs1 xa0 xa1 load address (low byte) read data (low byte) read data (high byte) load address (low byte) t bvdv t oldv t xlol t ohdz
250 atmega8535(l) 2502k?avr?10/06 notes: 1. t wlrh is valid for the write flash, write eeprom, write fuse bits and write lock bits commands. 2. t wlrh_ce is valid for the chip erase command. table 106. parallel programming characteristics, v cc = 5v 10% symbol parameter min typ max units v pp programming enable voltage 11.5 12.5 v i pp programming enable current 250 a t dvxh data and control valid before xtal1 high 67 ns t xlxh xtal1 low to xtal1 high 200 ns t xhxl xtal1 pulse width high 150 ns t xldx data and control hold after xtal1 low 67 ns t xlwl xtal1 low to wr low 0 ns t xlph xtal1 low to pagel high 0 ns t plxh pagel low to xtal1 high 150 ns t bvph bs1 valid before pagel high 67 ns t phpl pagel pulse width high 150 ns t plbx bs1 hold after pagel low 67 ns t wlbx bs2/1 hold after wr low 67 ns t plwl pagel low to wr low 67 ns t bvwl bs1 valid to wr low 67 ns t wlwh wr pulse width low 150 ns t wlrl wr low to rdy/bsy low 0 1 s t wlrh wr low to rdy/bsy high (1) 3.7 4.5 ms t wlrh_ce wr low to rdy/bsy high for chip erase (2) 7.5 9 ms t xlol xtal1 low to oe low 0 ns t bvdv bs1 valid to data valid 0 250 ns t oldv oe low to data valid 250 ns t ohdz oe high to data tri-stated 250 ns
251 atmega8535(l) 2502k?avr?10/06 serial downloading both the flash and eeprom memory arrays can be programmed using the serial spi bus while reset is pulled to gnd. the serial interface consists of pins sck, mosi (input), and miso (output). after reset is set low, the programming enable instruction needs to be executed first before program/ erase operations can be executed. note, in table 107 on page 251, the pin mapping for spi programming is listed. not all parts use the spi pins dedicated for the internal spi interface. serial programming pin mapping figure 124. serial programming and verify (1) notes: 1. if the device is clocked by the internal oscillator, it is no need to connect a clock source to the xtal1 pin. 2. vcc - 0.3 < avcc < vcc + 0.3. however, avcc should always be within 2.7 - 5.5v. when programming the eeprom, an auto-erase cy cle is built into the self-timed pro- gramming operation (in the serial mode only ) and there is no need to first execute the chip erase instruction. the chip erase operation turns the content of every memory location in both the program and eeprom arrays into 0xff. depending on cksel fuses, a valid clock must be present. the minimum low and high periods for the serial clock (sck) input are defined as follows: low:> 2 cpu clock cycles for f ck < 12 mhz, 3 cpu clock cycles for f ck 12 mhz high:> 2 cpu clock cycles for f ck < 12 mhz, 3 cpu clock cycles for f ck 12 mhz table 107. pin mapping serial programming symbol pins i/o description mosi pb5 i serial data in miso pb6 o serial data out sck pb7 i serial clock vcc gnd xtal1 sck miso mosi reset pb5 pb6 pb7 2.7 - 5.5v avcc 2.7 - 5.5v (2)
252 atmega8535(l) 2502k?avr?10/06 serial programming algorithm when writing serial data to the atmega8535, data is clocked on the rising edge of sck. when reading data from the atmega8535, data is clocked on the falling edge of sck. see figure 125 for timing details. to program and verify the atmega8535 in the serial programming mode, the following sequence is recommended (see four byte instruction formats in table 109 ): 1. power-up sequence: apply power between v cc and gnd while reset and sck are set to ?0?. in some systems, the programmer can not guarantee that sck is held low during power-up. in this case, reset must be given a positive pulse of at least two cpu clock cycles duration after sck has been set to ?0?. 2. wait for at least 20 ms and enable serial programming by sending the program- ming enable serial instruction to pin mosi. 3. the serial programming instructions will not work if the communication is out of synchronization. when in synchronization the second byte (0x53), will echo back when issuing the third byte of the programming enable instruction. whether the echo is correct or not, all four bytes of the instruction must be transmitted. if the 0x53 did not echo back, give reset a positive pulse and issue a new program- ming enable command. 4. the flash is programmed one page at a time. the page size is found in table 104 on page 241. the memory page is loaded one byte at a time by supplying the 6 lsb of the address and data together with the load program memory page instruction. to ensure correct loading of the page, the data low byte must be loaded before data high byte is applied for a given address. the program memory page is stored by loading the write program memory page instruction with the 8 msb of the address. if polling is not used, the user must wait at least t wd_flash before issuing the next page. (see table 108.) accessing the serial programming interface before the flash write operation completes can result in incorrect programming. 5. the eeprom array is programmed one byte at a time by supplying the address and data together with th e appropriate write instru ction. an eeprom memory location is first automatically erased bef ore new data is written. if polling is not used, the user must wait at least t wd_eeprom before issuing the next byte. (see table 108). in a chip erased device, no 0xffs in the data file(s) need to be programmed. 6. any memory location can be verified by using the read instruction which returns the content at the selected address at serial output miso. 7. at the end of the programming session, reset can be set high to commence normal operation. 8. power-off sequence (if needed): set reset to ?1?. tu r n v cc power off. data polling flash when a page is being programmed into the flash, reading an address location within the page being pr ogrammed will give the valu e 0xff. at the time the device is ready for a new page, the programmed value will read correctly. this is used to determine when the next page can be written. note that the entire page is written simultaneously and any address within the page can be used for polling. data polling of the flash will not work for the value 0xff, so when programming this value, the user will have to wait for at least t wd_flash before programming the next page. as a chip erased device contains 0xff in all locations, programming of addresses that are meant to contain 0xff, can be skipped. see table 108 for t wd_flash value.
253 atmega8535(l) 2502k?avr?10/06 data polling eeprom when a new byte has been written and is being programmed into eeprom, reading the address location being programme d will give the value 0xff. at the time the device is ready for a new byte, the programmed value will read correctly. this is used to deter- mine when the next byte can be written. this will not work for the value 0xff, but the user should have the following in mind: as a chip erased device contains 0xff in all locations, programming of addresses that ar e meant to contain 0xff, can be skipped. this does not apply if the eeprom is reprog rammed without chip erasing the device. in this case, data polling cannot be used for the va lue 0xff, and the user will have to wait at least t wd_eeprom before programming the next byte. see table 108 for t wd_eeprom value. figure 125. serial programming waveforms table 108. minimum wait delay befo re writing the next fl ash or eeprom location symbol minimum wait delay t wd_flash 4.5 ms t wd_eeprom 9.0 ms t wd_erase 9.0 ms t wd_fuse 4.5 ms msb msb lsb lsb serial clock input (sck) serial data input (mosi) (miso) sample serial data output
254 atmega8535(l) 2502k?avr?10/06 spi serial programming characteristics for characteristics of the spi module, see ?spi timing characteristics? on page 261. table 109. serial programmin g instruction set a = address high bits, b = address low bits, h = 0 - low byte, 1 - high byte, o = data out, i = data in, x = don?t care instruction instruction format operation byte 1 byte 2 byte 3 byte4 programming enable 1010 1100 0101 0011 xxxx xxxx xxxx xxxx enable serial programming after reset goes low. chip erase 1010 1100 100x xxxx xxxx xxxx xxxx xxxx chip erase eeprom and flash. read program memory 0010 h 000 0000 aaaa bbbb bbbb oooo oooo read h (high or low) data o from program memory at word address a : b . load program memory page 0100 h 000 0000 xxxx xxx b bbbb iiii iiii write h (high or low) data i to program memory page at word address b . data low byte must be loaded before data high byte is applied within the same address. write program memory page 0100 1100 0000 aaaa bbb x xxxx xxxx xxxx write program memory page at address a : b . read eeprom memory 1010 0000 00xx xxx a bbbb bbbb oooo oooo read data o from eeprom memory at address a : b . write eeprom memory 1100 0000 00xx xxx a bbbb bbbb iiii iiii write data i to eeprom memory at address a : b . read lock bits 0101 1000 0000 0000 xxxx xxxx xx oo oooo read lock bits. ?0? = programmed, ?1? = unprogrammed. see table 96 on page 237 for details. write lock bits 1010 1100 111x xxxx xxxx xxxx 11 ii iiii write lock bits. set bits = ?0? to program lock bits. see table 96 on page 237 for details. read signature byte 0011 0000 00xx xxxx xxxx xx bb oooo oooo read signature byte o at address b . write fuse bits 1010 1100 1 010 0000 xxxx xxxx iiii iiii set bits = ?0? to program, ?1? to unprogram. see table 99 on page 239 for details. write fuse high bits 1010 1100 1 010 1000 xxxx xxxx iiii iiii set bits = ?0? to program, ?1? to unprogram. see table 98 on page 238 for details. read fuse bits 0101 0000 0 000 0000 xxxx xxxx oooo oooo read fuse bits. ?0? = programmed, ?1? = unprogrammed. see table 99 on page 239 for details. read fuse high bits 0101 1000 0 000 1000 xxxx xxxx oooo oooo read fuse high bits. ?0? = pro- grammed, ?1? = unprogrammed. see table 98 on page 238 for details. read calibration byte 0011 1000 00xx xxxx 0000 00 bb oooo oooo read calibration byte
255 atmega8535(l) 2502k?avr?10/06 electrical characteristics dc characteristics absolute maximum ratings* operating temperature.................................. -55 c to +125 c *notice: stresses beyond those listed under ?absolute maximum ratings? may cause permanent dam- age to the device. this is a stress rating only and functional operation of the device at these or other conditions beyond those indicated in the operational sections of this specification is not implied. exposure to absolute maximum rating conditions for extended periods may affect device reliability. storage temperature ..................................... -65c to +150c voltage on any pin except reset with respect to ground ................................-0.5v to v cc +0.5v voltage on reset with respect to ground......-0.5v to +13.0v maximum operating voltage ............................................ 6.0v dc current per i/o pin ............................................... 40.0 ma dc current v cc and gnd pins .......... .............. 200.0 pdip og 400 ma tqfp/mlf/plccma t a = -40 c to 85 c, v cc = 2.7v to 5.5v (unless otherwise noted) symbol parameter condition min typ max units v il input low voltage except xtal1 and reset pins v cc =2.7v - 5.5v -0.5 0.2 v cc (1) v v ih input high voltage except xtal1 and reset pins v cc =2.7v - 5.5v 0.6 v cc (2) v cc + 0.5 v v il1 input low voltage xtal1 pin v cc =2.7v - 5.5v -0.5 0.1 v cc (1) v v ih1 input high voltage xtal1 pin v cc =2.7v - 5.5v 0.8 v cc (2) v cc + 0.5 v v il2 input low voltage reset pin v cc =2.7v - 5.5v -0.5 0.2 v cc v v ih2 input high voltage reset pin v cc =2.7v - 5.5v 0.9 v cc (2) v cc + 0.5 v v ol output low voltage (3) (ports a,b,c,d) i ol = 20 ma, v cc = 5v i ol = 10 ma, v cc = 3v 0.7 0.5 v v v oh output high voltage (4) (ports a,b,c,d) i oh = -20 ma, v cc = 5v i oh = -10 ma, v cc = 3v 4.2 2.2 v v i il input leakage current i/o pin v cc = 5.5 v, p i n l o w (absolute value) 1a i ih input leakage current i/o pin v cc = 5.5 v, pin high (absolute value) 1a r rst reset pull-up resistor 30 60 k r pu i/o pin pull-up resistor 20 50 k
256 atmega8535(l) 2502k?avr?10/06 notes: 1. ?max? means the highest value where the pin is guaranteed to be read as low. 2. ?min? means the lowest value where t he pin is guaranteed to be read as high. 3. although each i/o port can sink more than the test conditions (20ma at v cc = 5v, 10ma at v cc = 3v) under steady state conditions (non-transient), th e following must be observed: pdip package: 1] the sum of all iol, for all ports, should not exceed 200 ma. 2] the sum of all iol, for port a0 - a7, should not exceed 100 ma. 3] the sum of all iol, for ports b0 - b7,c0 - c7 , d0 - d7 and xtal2, should not exceed 100 ma. plcc/mlf/tqfp package: 1] the sum of all iol, for all ports, should not exceed 400 ma. 2] the sum of all iol, for ports a0 - a7, should not exceed 100 ma. 3] the sum of all iol, for ports b0 - b3, should not exceed 100 ma. 4] the sum of all iol, for ports b4 - b7, should not exceed 100 ma. 5] the sum of all iol, for ports c0 - c3, should not exceed 100 ma. 6] the sum of all iol, for ports c4 - c7, should not exceed 100 ma. 7] the sum of all iol, for ports d0 - d3 and xtal2, should not exceed 100 ma. 8] the sum of all iol, for ports d4 - d7, should not exceed 100 ma. if iol exceeds the test condition, vol may exceed the related specification. pins are not guar anteed to sink current greater than the listed test condition. 4. although each i/o port can source more than the test conditions (20ma at v cc = 5v, 10ma at v cc = 3v) under steady state conditions (non-transient), th e following must be observed: pdip package: 1] the sum of all ioh, for a ll ports, should not exceed 200 ma. 2] the sum of all ioh, for port a0 - a7, should not exceed 100 ma. 3] the sum of all ioh, for ports b0 - b7,c0 - c7 , d0 - d7 and xtal2, should not exceed 100 ma. plcc/mlf/tqfp package: 1] the sum of all ioh, for a ll ports, should not exceed 400 ma. 2] the sum of all ioh, for ports a0 - a7, should not exceed 100 ma. 3] the sum of all ioh, for ports b0 - b3, should not exceed 100 ma. 4] the sum of all ioh, for ports b4 - b7, should not exceed 100 ma. 5] the sum of all ioh, for ports c0 - c3, should not exceed 100 ma. 6] the sum of all ioh, for ports c4 - c7, should not exceed 100 ma. 7] the sum of all ioh, for ports d0 - d3 and xtal2, should not exceed 100 ma. 8] the sum of all ioh, for ports d4 - d7, should not exceed 100 ma i cc power supply current active 4 mhz, v cc = 3v ( atmega8535 l) 4ma active 8 mhz, v cc = 5v ( atmega8535 ) 14 ma idle 4 mhz, v cc = 3v ( atmega8535 l) 3ma idle 8 mhz, v cc = 5v ( atmega8535 ) 10 ma power-down mode (5) wdt enabled, v cc = 3v < 10 a wdt disabled, v cc = 3v < 3 a v acio analog comparator input offset voltage v cc = 5v v in = v cc /2 40 mv i aclk analog comparator input leakage current v cc = 5v v in = v cc /2 -50 50 na t acpd analog comparator propagation delay v cc = 2.7v v cc = 4.0v 750 500 ns t a = -40 c to 85 c, v cc = 2.7v to 5.5v (unless otherwise noted) (continued) symbol parameter condition min typ max units
257 atmega8535(l) 2502k?avr?10/06 if ioh exceeds the test condition, voh may exceed the rela ted specification. pins are not guaranteed to source current greater than the listed test condition. 5. minimum v cc for power-down is 2.5v.
258 atmega8535(l) 2502k?avr?10/06 external clock drive waveforms figure 126. external clock drive waveforms external clock drive notes: 1. r should be in the range 3 k - 100 k , and c should be at least 20 pf. the c values given in the table includes pin capacitance. this will vary with package type. 2. the frequency will vary with package type and board layout. v il1 v ih1 table 110. external clock drive symbol parameter v cc = 2.7v to 5.5 vv cc = 4.5v to 5.5 v units min max min max 1/t clcl oscillator frequency 0 8 0 16 mhz t clcl clock period 125 62.5 ns t chcx high time 50 25 ns t clcx low time 50 25 ns t clch rise time 1.6 0.5 s t chcl fall time 1.6 0.5 s t clcl change in period from one clock cycle to the next 22% table 111. external rc oscillator, typical frequencies r [k ] (1) c [pf] f (2) 33 22 650 khz 10 22 2.0 mhz
259 atmega8535(l) 2502k?avr?10/06 two-wire serial interface characteristics table 112 describes the requirements for devices connected to the two-wire serial bus. the atmega8535 two-wire serial interface meets or exceeds these requirements under the noted conditions. timing symbols refer to figure 127. notes: 1. in atmega8535, this parameter is characterized and not 100% tested. 2. required only for f scl > 100 khz. 3. c b = capacitance of one bus line in pf. table 112. two-wire serial bus requirements symbol parameter condition min max units vil input low voltage -0.5 0.3 v cc v vih input high voltage 0.7 v cc v cc + 0.5 v vhys (1) hysteresis of schmitt trigger inputs 0.05 v cc (2) ?v vol (1) output low voltage 3 ma sink current 0 0.4 v tr (1) rise time for both sda and scl 20 + 0.1c b (3)(2) 300 ns tof (1) output fall time from v ihmin to v ilmax 10 pf < c b < 400 pf (3) 20 + 0.1c b (3)(2) 250 ns tsp (1) spikes suppressed by input filter 0 50 (2) ns i i input current each i/o pin 0.1v cc < v i < 0.9v cc -10 10 a c i (1) capacitance for each i/o pin ? 10 pf f scl scl clock frequency f ck (4) > max(16f scl , 250khz) (5) 0 400 khz rp value of pull-up resistor f scl 100 khz f scl > 100 khz t hd;sta hold time (repeated) start condition f scl 100 khz 4.0 ? s f scl > 100 khz 0.6 ? s t low low period of the scl clock f scl 100 khz (6) 4.7 ? s f scl > 100 khz (7) 1.3 ? s t high high period of the scl clock f scl 100 khz 4.0 ? s f scl > 100 khz 0.6 ? s t su;sta set-up time for a repeated start condition f scl 100 khz 4.7 ? s f scl > 100 khz 0.6 ? s t hd;dat data hold time f scl 100 khz 0 3.45 s f scl > 100 khz 0 0.9 s t su;dat data setup time f scl 100 khz 250 ? ns f scl > 100 khz 100 ? ns t su;sto setup time for stop condition f scl 100 khz 4.0 ? s f scl > 100 khz 0.6 ? s t buf bus free time between a stop and start condition f scl 100 khz 4.7 ? s f scl > 100 khz 1.3 ? s v cc 0.4v ? 3ma ---------------------------- 1000ns c b ------------------- v cc 0.4v ? 3ma ---------------------------- 300ns c b --------------- -
260 atmega8535(l) 2502k?avr?10/06 4. f ck = cpu clock frequency. 5. this requirement applies to all atmega8535 two-wire serial interface operation. other devices connected to the two-wire serial bus need only obey the general f scl requirement. 6. the actual low period generated by the atmega8535 two-wire serial interface is (1/f scl - 2/f ck ), thus f ck must be greater than 6 mhz for the low time requir ement to be strictly met at f scl = 100 khz. 7. the actual low period generated by the atmega8535 two-wire serial interface is (1/f scl - 2/f ck ), thus the low time require- ment will not be strictly met for f scl > 308 khz when f ck = 8 mhz. still, atmega8535 devices connected to the bus may communicate at full speed (400 khz) with other atmega8535 de vices, as well as any other device with a proper t low accep- tance margin. figure 127. two-wire serial bus timing t su;sta t low t high t low t of t hd;sta t hd;dat t su;dat t su;sto t buf scl sda t r
261 atmega8535(l) 2502k?avr?10/06 spi timing characteristics see figure 128 and figure 129 for details. table 113. spi timing parameters description mode min typ max 1 sck period master see table 59 ns 2 sck high/low master 50% duty cycle 3 rise/fall time master 3.6 4 setup master 10 5hold master 10 6 out to sck master 5 ? t sck 7 sck to out master 10 8 sck to out high master 10 9 ss low to out slave 15 10 sck period slave 4 ? t ck 11 sck high/low slave 2 ? t ck 12 rise/fall time slave 1.6 ns 13 setup slave 10 ns 14 hold slave 10 15 sck to out slave 15 16 sck to ss high slave 20 17 ss high to tri-state slave 10 18 ss low to sck slave 2 ? t ck
262 atmega8535(l) 2502k?avr?10/06 figure 128. spi interface timing requirements (master mode) figure 129. spi interface timing requirements (slave mode) mosi (data output) sck (cpol = 1) miso (data input) sck (cpol = 0) ss msb lsb lsb msb ... ... 61 22 3 45 8 7 miso (data output) sck (cpol = 1) mosi (data input) sck (cpol = 0) ss msb lsb lsb msb ... ... 10 11 11 12 13 14 17 15 9 x 16 18
263 atmega8535(l) 2502k?avr?10/06 adc characteristics notes: 1. values are guidelines only. 2. minimum for av cc is 2.7v. 3. maximum for av cc is 5.5v table 114. adc characteristics, single ended channels symbol parameter condition min (1) typ (1) max (1) units resolution single ended conversion 10 bits absolute accuracy (including inl, dnl, quantization error, gain and offset error) single ended conversion v ref = 4v, v cc = 4v adc clock = 200 khz 1.5 lsb single ended conversion v ref = 4v, v cc = 4v adc clock = 1 mhz 3lsb single ended conversion v ref = 4v, v cc = 4v adc clock = 200 khz noise reduction mode 1.5 lsb single ended conversion v ref = 4v, v cc = 4v adc clock = 1 mhz noise reduction mode 3lsb integral non-linearity (inl) single ended conversion v ref = 4v, v cc = 4v adc clock = 200 khz 0.75 lsb differential non-linearity (dnl) single ended conversion v ref = 4v, v cc = 4v adc clock = 200 khz 0.25 lsb gain error single ended conversion v ref = 4v, v cc = 4v adc clock = 200 khz 0.75 lsb offset error single ended conversion v ref = 4v, v cc = 4v adc clock = 200 khz 0.75 lsb clock frequency 50 1000 khz conversion time 13 260 s avcc analog supply voltage v cc - 0.3 (2) v cc + 0.3 (3) v v ref reference voltage 2.0 avcc v v in input voltage gnd v ref v adc conversion output 0 1023 lsb input bandwidth 38.5 khz v int internal voltage reference 2.3 2.56 2.7 v r ref reference input resistance 32 k r ain analog input resistance 100 m
264 atmega8535(l) 2502k?avr?10/06 table 115. adc characteristics, differential channels symbol parameter condition min (1) typ (1) max (1) units resolution gain = 1x 10 bits gain = 10x 10 bits gain = 200x 10 bits absolute accuracy gain = 1x v ref = 4v, v cc = 5v adc clock = 50 - 200 khz 18 lsb gain = 10x v ref = 4v, v cc = 5v adc clock = 50 - 200 khz 18 lsb gain = 200x v ref = 4v, v cc = 5v adc clock = 50 - 200 khz 6lsb integral non-linearity (inl) (accuracy after calibration for offset and gain error) gain = 1x v ref = 4v, v cc = 5v adc clock = 50 - 200 khz 0.75 lsb gain = 10x v ref = 4v, v cc = 5v adc clock = 50 - 200 khz 0.75 lsb gain = 200x v ref = 4v, v cc = 5v adc clock = 50 - 200 khz 3.5 lsb gain error gain = 1x 1.7 % gain = 10x 1.6 % gain = 200x 0.3 % offset error gain = 1x v ref = 4v, v cc = 5v adc clock = 50 - 200 khz 2lsb gain = 10x v ref = 4v, v cc = 5v adc clock = 50 - 200 khz 2.5 lsb gain = 200x v ref = 4v, v cc = 5v adc clock = 50 - 200 khz 3.5 lsb clock frequency 50 200 khz conversion time 65 260 s avcc analog supply voltage v cc - 0.3 (2) v cc + 0.3 (3) v v ref reference voltage 2.0 avcc- 0.5 v v in input voltage gnd v cc v v diff input differential voltage -v ref /gain v ref /gain v adc conversion output -511 511 lsb input bandwidth 4khz
265 atmega8535(l) 2502k?avr?10/06 notes: 1. values are guidelines only. 2. minimum for avcc is 2.7v. 3. maximum for avcc is 5.5v. v int internal voltage reference 2.3 2.56 2.7 v r ref reference input resistance 32 k r ain analog input resistance 100 m table 115. adc characteristics, differential channels (continued) symbol parameter condition min (1) typ (1) max (1) units
266 atmega8535(l) 2502k?avr?10/06 atmega8535 typical characteristics the following charts show typical behavior. these figures are not tested during manu- facturing. all current consumption measurements are performed with all i/o pins configured as inputs and with internal pull-ups enabled. a sine wave generator with rail- to-rail output is used as clock source. the power consumption in power-down mode is independent of clock selection. the current consumption is a function of several factors such as: operating voltage, operating frequency, loading of i/o pins, switching rate of i/o pins, code executed and ambient temperature. the dominating factors are operating voltage and frequency. the current drawn from capacitive loaded pins may be estimated (for one pin) as c l * v cc *f where c l = load capacitance, v cc = operating voltage and f = average switch- ing frequency of i/o pin. the parts are characterized at frequencies higher than test limits. parts are not guaran- teed to function properly at frequencies higher than the ordering code indicates. the difference between current consumption in power-down mode with watchdog timer enabled and power-down mode with watchdog timer disabled represents the dif- ferential current drawn by the watchdog timer. active supply current figure 130. active supply current vs. frequency (0.1 - 1.0 mhz) active supply current vs. frequency 0.1 - 1.0 mhz 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0. 9 1 frequency (mhz) i cc (ma) 5.5v 5.0v 4.5v 3.3v 3.0v 2.7v 4.0v
267 atmega8535(l) 2502k?avr?10/06 figure 131. active supply current vs. frequency (1 - 16 mhz) figure 132. active supply current vs. v cc (internal rc oscillator, 8 mhz) active supply current vs. frequency 1 - 16 mhz 0 5 10 15 20 25 0246810121416 frequency (mhz) i cc (ma) 5.5v 5.0v 4.5v 3.3v 3.0v 2.7v 4.0v active supply current vs. v cc internal rc oscillator, 8 mhz 0 2 4 6 8 10 12 14 16 18 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) 85 c 25 c -40 c
268 atmega8535(l) 2502k?avr?10/06 figure 133. active supply current vs. v cc (internal rc oscillator, 4 mhz) figure 134. active supply current vs. v cc (internal rc oscillator, 2 mhz) active supply current vs. v cc internal rc oscillator, 4 mhz 0 1 2 3 4 5 6 7 8 9 10 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) 85 c 25 c -40 c active supply current vs. v internal rc oscillator, 2 mhz 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 2.5 3 3.5 4 4.5 5 5.5 vcc (v) icc (ma) 85c 25c -40c cc
269 atmega8535(l) 2502k?avr?10/06 figure 135. active supply current vs. v cc (internal rc oscillator, 1 mhz) figure 136. active supply current vs. v cc (32 khz external oscillator) active supply current vs. v cc internal rc oscillator, 1 mhz 0 0.5 1 1.5 2 2.5 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) 85 c 25 c -40 c active supply current vs. v cc 32khz external oscillator 0 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) 25 c
270 atmega8535(l) 2502k?avr?10/06 idle supply current figure 137. idle supply current vs. frequency (0.1 - 1.0 mhz) figure 138. idle supply current vs. frequency (1 - 16 mhz) idle supply current vs. frequency 0.1 - 1.0 mhz 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0. 9 1 frequency (mhz) i cc (ma) 5.5v 4.5v 4.0v 3.3v 3.0v 2.7v 5.0v idle supply current vs. frequency 1 - 16 mhz 0 2 4 6 8 10 12 14 0246810121416 frequency (mhz) i cc (ma) 5.5v 4.5v 4.0v 3.3v 3.0v 2.7v 5.0v
271 atmega8535(l) 2502k?avr?10/06 figure 139. idle supply current vs. v cc (internal rc oscillator, 8 mhz) figure 140. idle supply current vs. v cc (internal rc oscillator, 4 mhz) idle supply current vs. v cc internal rc oscillator, 8 mhz 0 1 2 3 4 5 6 7 8 9 10 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) 85 c 25 c -40 c idle supply current vs. v cc internal rc oscillator, 4 mhz 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) 85 c 25 c -40 c
272 atmega8535(l) 2502k?avr?10/06 figure 141. idle supply current vs. v cc (internal rc oscillator, 2 mhz) figure 142. idle supply current vs. v cc (internal rc oscillator, 1 mhz) idle supply current vs. v cc internal rc oscillator, 2 mhz 0 0.5 1 1.5 2 2.5 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) 85 c 25 c -40 c idle supply current vs. v cc internal rc oscillator, 1 mhz 0 0.2 0.4 0.6 0.8 1 1.2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) 85 c 25 c -40 c
273 atmega8535(l) 2502k?avr?10/06 figure 143. idle supply current vs. v cc (32 khz external oscillator) power-down supply current figure 144. power-down supply current vs. v cc (watchdog timer disabled) idle supply current vs. v cc 32khz external oscillator 0 0.005 0.01 0.015 0.02 0.025 0.03 0.035 0.04 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) 25 c power-down supply current vs. v cc watchdog timer disabled 0 0.5 1 1.5 2 2.5 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ua) 85 c 25 c -40 c
274 atmega8535(l) 2502k?avr?10/06 figure 145. power-down supply current vs. v cc (watchdog timer enabled) power-save supply current figure 146. power-save supply current vs. v cc (watchdog timer disabled) power-down supply current vs. v cc watchdog timer enabled 0 0.005 0.01 0.015 0.02 0.025 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) 85 c 25 c -40 c power-save supply current vs. v cc watchdog timer disabled 0 2 4 6 8 10 12 14 16 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ua) 25 c
275 atmega8535(l) 2502k?avr?10/06 standby supply current figure 147. standby supply current vs. v cc (455 khz resonator, watchdog timer disabled) figure 148. standby supply current vs. v cc (1 mhz resonator, watchdog timer disabled) standby supply current vs. v cc 455 khz resonator, watchdog timer disabled 0 10 20 30 40 50 60 70 80 9 0 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ua) standby supply current vs. v cc 1 mhz resonator, watchdog timer disabled 0 10 20 30 40 50 60 70 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ua)
276 atmega8535(l) 2502k?avr?10/06 figure 149. standby supply current vs. v cc (2 mhz resonator, watchdog timer disabled) figure 150. standby supply current vs. v cc (2 mhz xtal, watchdog timer disabled) standby supply current vs. v cc 2 mhz resonator, watchdog timer disabled 0 10 20 30 40 50 60 70 80 9 0 100 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ua) standby supply current vs. v cc 2 mhz xtal, watchdog timer disabled 0 10 20 30 40 50 60 70 80 9 0 100 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ua)
277 atmega8535(l) 2502k?avr?10/06 figure 151. standby supply current vs. v cc (4 mhz resonator, watchdog timer disabled) figure 152. standby supply current vs. v cc (4 mhz xtal, watchdog timer disabled) standby supply current vs. v cc 4 mhz resonator, watchdog timer disabled 0 20 40 60 80 100 120 140 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ua) standby supply current vs. v cc 4 mhz xtal, watchdog timer disabled 0 20 40 60 80 100 120 140 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ua)
278 atmega8535(l) 2502k?avr?10/06 figure 153. standby supply current vs. v cc (6 mhz resonator, watchdog timer disabled) figure 154. standby supply current vs. v cc (6 mhz xtal, watchdog timer disabled) standby supply current vs. v cc 6 mhz resonator, watchdog timer disabled 0 20 40 60 80 100 120 140 160 180 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ua) standby supply current vs. v cc 6 mhz xtal, watchdog timer disabled 0 20 40 60 80 100 120 140 160 180 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ua)
279 atmega8535(l) 2502k?avr?10/06 pin pullup figure 155. i/o pin pull-up resistor current vs. input voltage (v cc = 5v) figure 156. i/o pin pull-up resistor current vs. input voltage (v cc = 2.7v) i/o pin pull-up resistor current vs. input voltage vcc = 5v 0 20 40 60 80 100 120 140 160 0123 v op (v) i op (ua) 85 c 25 c -40 c i/o pin pull-up resistor current vs. input voltage vcc = 2.7v 0 10 20 30 40 50 60 70 80 0 0.5 1 1.5 2 2.5 3 v op (v) i op (ua) 85 c 25 c -40 c
280 atmega8535(l) 2502k?avr?10/06 figure 157. reset pull-up resistor current vs. reset pin voltage (v cc = 5v) figure 158. reset pull-up resistor current vs. reset pin voltage (v cc = 2.7v) reset pull-up resistor current vs. reset pin voltage vcc = 5v 0 20 40 60 80 100 120 0123 v reset (v) i reset (ua) 85 c 25 c -40 c reset pull-up resistor current vs. reset pin voltage vcc = 2.7v 0 10 20 30 40 50 60 0 0.5 1 1.5 2 2.5 3 v reset (v) i reset (ua) 85 c 25 c -40 c
281 atmega8535(l) 2502k?avr?10/06 pin driver strength figure 159. i/o pin source current vs. output voltage (v cc = 5v) figure 160. i/o pin source current vs. output voltage (v cc = 2.7v) i/o pin source current vs. output voltage vcc = 5v 0 10 20 30 40 50 60 70 80 9 0 2.5 3 3.5 4 4.5 5 5.5 v oh (v) i oh (ma) 85 c 25 c -40 c i/o pin source current vs. output voltage vcc = 2.7v 0 5 10 15 20 25 30 0 0.5 1 1.5 2 2.5 3 v oh (v) i oh (ma) 85 c 25 c -40 c
282 atmega8535(l) 2502k?avr?10/06 figure 161. i/o pin sink current vs. output voltage (v cc = 5v) figure 162. i/o pin sink current vs. output voltage (v cc = 2.7v) i/o pin sink current vs. output voltage vcc = 5v 0 10 20 30 40 50 60 70 80 9 0 0 0.5 1 1.5 2 2.5 v ol (v) i ol (ma) 85 c 25 c -40 c i/o pin sink current vs. output voltage vcc = 2.7v 0 5 10 15 20 25 30 35 0 0.5 1 1.5 2 2.5 v ol (v) i ol (ma) 85 c 25 c -40 c
283 atmega8535(l) 2502k?avr?10/06 pin thresholds and hysteresis figure 163. i/o pin input threshold voltage vs. v cc (v ih , i/o pin read as '1') figure 164. i/o pin input threshold voltage vs. v cc (v il , i/o pin read as '0') i/o pin input threshold voltage vs. v cc vih, io pin read as '1' 0 0.5 1 1.5 2 2.5 2.5 3 3.5 4 4.5 5 5.5 v cc (v) threshold (v) 85 c 25 c -40 c i/o pin input threshold voltage vs. v cc vil, io pin read as '0' 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) threshold (v) 85 c 25 c -40 c
284 atmega8535(l) 2502k?avr?10/06 figure 165. i/o pin input hysteresis vs. v cc figure 166. reset input thresh old voltage vs. v cc (v ih , reset pin read as '1') i/o pin input hysteresis vs. v cc 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 2.5 3 3.5 4 4.5 5 5.5 v cc (v) threshold (v) 85 c 25 c -40 c reset input threshold voltage vs. v cc vih, io pin read as '1' 0 0.5 1 1.5 2 2.5 2.5 3 3.5 4 4.5 5 5.5 v cc (v) threshold (v) 85 c 25 c -40 c
285 atmega8535(l) 2502k?avr?10/06 figure 167. reset input thresh old voltage vs. v cc (v il , reset pin read as '0') figure 168. reset input pin hysteresis vs. v cc reset input threshold voltage vs. v cc vil, io pin read as '0' 0.5 1 1.5 2 2.5 3 2.5 3 3.5 4 4.5 5 5.5 v cc (v) threshold (v) 85 c 25 c -40 c reset input pin hysteresis vs. v cc 0 0.1 0.2 0.3 0.4 0.5 0.6 2.5 3 3.5 4 4.5 5 5.5 v cc (v) threshold (v) 85 c 25 c -40 c
286 atmega8535(l) 2502k?avr?10/06 bod thresholds and analog comparator offset figure 169. bod thresholds vs. temperature (bod level is 4.0v) figure 170. bod thresholds vs. temperature (bod level is 2.7v) bod thresholds vs. temperature bod level is 4.0 v 3.7 3.75 3.8 3.85 3. 9 3. 9 5 4 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 9 0 100 temperature (c) threshold (v) rising v cc falling v cc bod thresholds vs. temperature bod level is 2.7 v 2.5 2.55 2.6 2.65 2.7 2.75 2.8 2.85 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 9 0 100 temperature (c) threshold (v) rising v cc falling v cc
287 atmega8535(l) 2502k?avr?10/06 figure 171. bandgap voltage vs. v cc figure 172. analog comparator offset voltage vs. common mode voltage (v cc = 5v) bandgap vs. v cc 1.208 1.21 1.212 1.214 1.216 1.218 1.22 1.222 1.224 1.226 2.5 3 3.5 4 4.5 5 5.5 vcc (v) bandgap voltage (v) 85c 25c -40c analog comparator offset voltage vs. common mode voltage vcc = 5v -0.006 -0.005 -0.004 -0.003 -0.002 -0.001 0 0.001 0.002 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 common mode voltage (v) comparator offset voltage (v) 85c 25c -40c
288 atmega8535(l) 2502k?avr?10/06 figure 173. analog comparator offset voltage vs. common mode voltage (v cc = 2.7v) internal oscillator speed figure 174. watchdog oscillator frequency vs. v cc analog comparator offset voltage vs. common mode voltage vcc = 2.7v -0.004 -0.003 -0.002 -0.001 0 0.001 0.002 0 0.5 1 1.5 2 2.5 3 common mode voltage (v) comparator offset voltage (v) 85c 25c -40c watchdog oscillator frequency vs. v cc 1000 1050 1100 1150 1200 1250 1300 2.5 3 3.5 4 4.5 5 5.5 v cc (v) f rc (khz) 85 c 25 c -40 c
289 atmega8535(l) 2502k?avr?10/06 figure 175. calibrated 8 mhz rc oscillator frequen cy vs. temperature figure 176. calibrated 8 mhz rc osc illator frequency vs. v cc calibrated 8 mhz rc oscillator frequency vs. temperature 6 6.5 7 7.5 8 8.5 9 -50 -30 -10 10 30 50 70 9 0 110 temp (c?) f rc (mhz) 5.5v 2.7v 4.0v calibrated 8 mhz rc oscillator frequency vs. v cc 6.5 6.7 6. 9 7.1 7.3 7.5 7.7 7. 9 8.1 8.3 8.5 2.5 3 3.5 4 4.5 5 5.5 v cc (v) f rc (mhz) 85 c 25 c -40 c
290 atmega8535(l) 2502k?avr?10/06 figure 177. calibrated 8 mhz rc oscillator frequen cy vs. osccal value figure 178. calibrated 4 mhz rc oscillator frequen cy vs. temperature calibrated 8 mhz rc oscillator frequency vs.osccal value 0 2 4 6 8 10 12 14 16 18 0 1632486480 9 6 112 128 144 160 176 1 9 2 208 224 240 osccal value f rc (mhz) calibrated 4 mhz rc oscillator frequency vs. temperature 3.5 3.6 3.7 3.8 3. 9 4 4.1 4.2 -50 -30 -10 10 30 50 70 9 0 110 temp (c?) f rc (mhz) 5.5v 2.7v 4.0v
291 atmega8535(l) 2502k?avr?10/06 figure 179. calibrated 4 mhz rc osc illator frequency vs. v cc figure 180. calibrated 4 mhz rc oscillator frequen cy vs. osccal value calibrated 4 mhz rc oscillator frequency vs. v cc 3.4 3.5 3.6 3.7 3.8 3. 9 4 4.1 4.2 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) f rc (mhz) 85 c 25 c -40 c calibrated 4 mhz rc oscillator frequency vs. osccal value 0 1 2 3 4 5 6 7 8 9 0 1632486480 9 6 112 128 144 160 176 1 9 2 208 224 240 osccal value f rc (mhz)
292 atmega8535(l) 2502k?avr?10/06 figure 181. calibrated 2 mhz rc oscillator frequen cy vs. temperature figure 182. calibrated 2 mhz rc osc illator frequency vs. v cc calibrated 2 mhz rc oscillator frequency vs. temperature 1.75 1.8 1.85 1. 9 1. 9 5 2 2.05 2.1 -50 -30 -10 10 30 50 70 9 0 110 temp (c?) f rc (mhz) 5.5v 2.7v 4.0v calibrated 2 mhz rc oscillator frequency vs. v cc 1.7 1.75 1.8 1.85 1. 9 1. 9 5 2 2.05 2.1 2.15 2.5 3 3.5 4 4.5 5 5.5 v cc (v) f rc (mhz) 85 c 25 c -40 c
293 atmega8535(l) 2502k?avr?10/06 figure 183. calibrated 2 mhz rc oscillator frequen cy vs. osccal value figure 184. calibrated 1 mhz rc oscillator frequen cy vs. temperature calibrated 2 mhz rc oscillator frequency vs. osccal value 0 0.5 1 1.5 2 2.5 3 3.5 4 0 1632486480 9 6 112 128 144 160 176 1 9 2 208 224 240 osccal value f rc (mhz) calibrated 1 mhz rc oscillator frequency vs. temperature 0. 9 0. 9 2 0. 9 4 0. 9 6 0. 9 8 1 1.02 1.04 -50 -30 -10 10 30 50 70 9 0 110 temp (c?) f rc (mhz) 5.5v 2.7v 4.0v
294 atmega8535(l) 2502k?avr?10/06 figure 185. calibrated 1 mhz rc osc illator frequency vs. v cc figure 186. calibrated 1 mhz rc oscillator frequen cy vs. osccal value calibrated 1 mhz rc oscillator frequency vs. v cc 0.85 0.87 0.8 9 0. 9 1 0. 9 3 0. 9 5 0. 9 7 0. 99 1.01 1.03 1.05 2.5 3 3.5 4 4.5 5 5.5 v cc (v) f rc (mhz) 85 c 25 c -40 c calibrated 1 mhz rc oscillator frequency vs. osccal value 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2 0 1632486480 9 6 112 128 144 160 176 1 9 2 208 224 240 osccal value f rc (mhz)
295 atmega8535(l) 2502k?avr?10/06 current consumption of peripheral units figure 187. brownout detector current vs. v cc figure 188. adc current vs. v cc (aref = avcc) brownout detector current vs. v cc 0 0.005 0.01 0.015 0.02 0.025 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) 85 c 25 c -40 c adc current vs. v cc aref = avcc 0 100 200 300 400 500 600 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ua) 85 c 25 c -40 c
296 atmega8535(l) 2502k?avr?10/06 figure 189. aref external reference current vs. v cc figure 190. analog comparator current vs. v cc aref external reference current vs. v cc 0 50 100 150 200 250 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ua) 85 c 25 c -40 c analog comparator current vs. v cc 0 20 40 60 80 100 120 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ua) 85 c 25 c -40 c
297 atmega8535(l) 2502k?avr?10/06 figure 191. programming current vs. v cc current consumption in reset and reset pulsewidth figure 192. reset supply current vs. v cc (0.1 - 1.0 mhz, excluding current through the reset pull-up) programming current vs. v 0 2 4 6 8 10 12 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) 85 c 25 c -40 c cc reset supply current vs. v cc 0.1 - 1.0 mhz, excluding current through the reset pullup 0 0.5 1 1.5 2 2.5 3 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0. 9 1 frequency (mhz) i cc (ma) 5.5v 5.0v 4.5v 3.3v 3.0v 2.7v 4.0v
298 atmega8535(l) 2502k?avr?10/06 figure 193. reset supply current vs. v cc (1 - 20 mhz, excluding current through the reset pull-up) figure 194. reset pulse width vs. v cc reset supply current vs. v cc 1 - 20 mhz, excluding current through the reset pullup 0 5 10 15 20 25 0 2 4 6 8 101214161820 frequency (mhz) i cc (ma) 5.5v 5.0v 4.5v 3.3v 3.0v 2.7v 4.0v reset pulse width vs. v cc 0 200 400 600 800 1000 1200 2.5 3 3.5 4 4.5 5 5.5 v cc (v) pulsewidth (ns) 85c 25c -40c
299 atmega8535(l) 2502k?avr?10/06 . register summary address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page 0x3f (0x5f) sreg i t h s v n z c 10 0x3e (0x5e) sph ? ? ? ? ? ?sp9sp8 12 0x3d (0x5d) spl sp7 sp6 sp5 sp4 sp3 sp2 sp1 sp0 12 0x3c (0x5c) ocr0 timer/counter0 output compare register 85 0x3b (0x5b) gicr int1 int0 int2 ? ? ? ivsel ivce 49, 69 0x3a (0x5a) gifr intf1 intf0 intf2 ? ? ? ? ?70 0x39 (0x59) timsk ocie2 toie2 ticie1 ocie1a ocie1b toie1 ocie0 toie0 85, 115, 133 0x38 (0x58) tifr ocf2 tov2 icf1 ocf1 a ocf1b tov1 ocf0 tov0 86, 116, 134 0x37 (0x57) spmcr spmie rwwsb ? rwwsre blbset pgwrt pgers spmen 228 0x36 (0x56) twcr twint twea twsta twsto twwc twen ?twie 181 0x35 (0x55) mcucr sm2 se sm1 sm0 isc11 isc10 isc01 isc00 32, 68 0x34 (0x54) mcucsr ?isc2 ? ? wdrf borf extrf porf 40, 69 0x33 (0x53) tccr0 foc0 wgm00 com01 com00 wgm01 cs02 cs01 cs00 83 0x32 (0x52) tcnt0 timer/counter0 (8 bits) 85 0x31 (0x51) osccal oscillator calibration register 30 0x30 (0x50) sfior adts2 adts1 adts0 ? acme pud psr2 psr10 59,88,135,203,223 0x2f (0x4f) tccr1a com1a1 com1a0 com1b1 com1b0 foc1a foc1b wgm11 wgm10 110 0x2e (0x4e) tccr1b icnc1 ices1 ? wgm13 wgm12 cs12 cs11 cs10 113 0x2d (0x4d) tcnt1h timer/counter1 ? counter register high byte 114 0x2c (0x4c) tcnt1l timer/counter1 ? counter register low byte 114 0x2b (0x4b) ocr1ah timer/counter1 ? output compare register a high byte 114 0x2a (0x4a) ocr1al timer/counter1 ? output compare register a low byte 114 0x29 (0x49) ocr1bh timer/counter1 ? output compare register b high byte 114 0x28 (0x48) ocr1bl timer/counter1 ? output compare register b low byte 114 0x27 (0x47) icr1h timer/counter1 ? input capture register high byte 114 0x26 (0x46) icr1l timer/counter1 ? input capture register low byte 114 0x25 (0x45) tccr2 foc2 wgm20 com21 com20 wgm21 cs22 cs21 cs20 128 0x24 (0x44) tcnt2 timer/counter2 (8 bits) 130 0x23 (0x43) ocr2 timer/counter2 output compare register 131 0x22 (0x42) assr ? ? ? ? as2 tcn2ub ocr2ub tcr2ub 131 0x21 (0x41) wdtcr ? ? ? wdce wde wdp2 wdp1 wdp0 42 0x20 (1) (0x40) (1) ubrrh ursel ? ? ? ubrr[11:8] 169 ucsrc ursel umsel upm1 upm0 usbs ucsz1 ucsz0 ucpol 167 0x1f (0x3f) eearh ? ? ? ? ? ? ? eear8 19 0x1e (0x3e) eearl eeprom address register low byte 19 0x1d (0x3d) eedr eeprom data register 19 0x1c (0x3c) eecr ? ? ? ? eerie eemwe eewe eere 19 0x1b (0x3b) porta porta7 porta6 porta5 porta4 porta3 porta2 porta1 porta0 66 0x1a (0x3a) ddra dda7 dda6 dda 5 dda4 dda3 dda2 dda1 dda0 66 0x19 (0x39) pina pina7 pina6 pina 5 pina4 pina3 pina2 pina1 pina0 66 0x18 (0x38) portb portb7 portb6 portb 5 portb4 portb3 portb2 portb1 portb0 66 0x17 (0x37) ddrb ddb7 ddb6 ddb 5 ddb4 ddb3 ddb2 ddb1 ddb0 66 0x16 (0x36) pinb pinb7 pinb6 pinb 5 pinb4 pinb3 pinb2 pinb1 pinb0 67 0x15 (0x35) portc portc7 portc6 portc 5 portc4 portc3 portc2 portc1 portc0 67 0x14 (0x34) ddrc ddc7 ddc6 ddc5 ddc4 ddc3 ddc2 ddc1 ddc0 67 0x13 (0x33) pinc pinc7 pinc6 pinc5 pinc4 pinc3 pinc2 pinc1 pinc0 67 0x12 (0x32) portd portd7 portd6 portd 5 portd4 portd3 portd2 portd1 portd0 67 0x11 (0x31) ddrd ddd7 ddd6 ddd5 ddd4 ddd3 ddd2 ddd1 ddd0 67 0x10 (0x30) pind pind7 pind6 pind5 pind4 pind3 pind2 pind1 pind0 67 0x0f (0x2f) spdr spi data register 143 0x0e (0x2e) spsr spif wcol ? ? ? ? ? spi2x 143 0x0d (0x2d) spcr spie spe dord mstr cpol cpha spr1 spr0 141 0x0c (0x2c) udr usart i/o data register 164 0x0b (0x2b) ucsra rxc txc udre fe dor pe u2x mpcm 165 0x0a (0x2a) ucsrb rxcie txcie udrie rxen txen ucsz2 rxb8 txb8 166 0x09 (0x29) ubrrl usart baud rate register low byte 169 0x08 (0x28) acsr acd acbg aco aci acie acic acis1 acis0 203 0x07 (0x27) admux refs1 refs0 adlar mux4 mux3 mux2 mux1 mux0 219 0x06 (0x26) adcsra aden adsc adate adif adie adps2 adps1 adps0 221 0x05 (0x25) adch adc data register high byte 222 0x04 (0x24) adcl adc data register low byte 222 0x03 (0x23) twdr two-wire serial interface data register 183 0x02 (0x22) twar twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce 183 0x01 (0x21) twsr tws7 tws6 tws5 tws4 tws3 ? twps1 twps0 183
300 atmega8535(l) 2502k?avr?10/06 notes: 1. refer to the usart description for details on how to access ubrrh and ucsrc. 2. for compatibility with future devices, reserved bits should be written to zero if accessed. reserved i/o memory addresses should never be written. 3. some of the status flags are cleared by writing a logical one to them. note that the cbi and sbi instructions will operate on all bits in the i/o register, writing a one back into any flag read as set, thus clearing the flag. the cbi and sbi instruction s work with registers 0x00 to 0x1f only. 0x00 (0x20) twbr two-wire serial interface bit rate register 181 register summary (continued) address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page
301 atmega8535(l) 2502k?avr?10/06 instruction set summary mnemonics operands description operation flags #clocks arithmetic and logic instructions add rd, rr add two registers rd rd + rr z,c,n,v,h 1 adc rd, rr add with carry two registers rd rd + rr + c z,c,n,v,h 1 adiw rdl,k add immediate to word rdh:rdl rdh:rdl + k z,c,n,v,s 2 sub rd, rr subtract two registers rd rd - rr z,c,n,v,h 1 subi rd, k subtract constant from register rd rd - k z,c,n,v,h 1 sbc rd, rr subtract with carry two registers rd rd - rr - c z,c,n,v,h 1 sbci rd, k subtract with carry constant from reg. rd rd - k - c z,c,n,v,h 1 sbiw rdl,k subtract immediate from word rdh:rdl rdh:rdl - k z,c,n,v,s 2 and rd, rr logical and registers rd rd ? rr z,n,v 1 andi rd, k logical and register and constant rd rd ? k z,n,v 1 or rd, rr logical or registers rd rd v rr z,n,v 1 ori rd, k logical or register and constant rd rd v k z,n,v 1 eor rd, rr exclusive or registers rd rd rr z,n,v 1 com rd one?s complement rd 0xff ? rd z,c,n,v 1 neg rd two?s complement rd 0x00 ? rd z,c,n,v,h 1 sbr rd,k set bit(s) in register rd rd v k z,n,v 1 cbr rd,k clear bit(s) in register rd rd ? (0xff - k) z,n,v 1 inc rd increment rd rd + 1 z,n,v 1 dec rd decrement rd rd ? 1 z,n,v 1 tst rd test for zero or minus rd rd ? rd z,n,v 1 clr rd clear register rd rd rd z,n,v 1 ser rd set register rd 0xff none 1 mul rd, rr multiply unsigned r1:r0 rd x rr z,c 2 muls rd, rr multiply signed r1:r0 rd x rr z,c 2 mulsu rd, rr multiply signed with unsigned r1:r0 rd x rr z,c 2 fmul rd, rr fractional multiply unsigned r1:r0 (rd x rr) << 1 z,c 2 fmuls rd, rr fractional multiply signed r1:r0 (rd x rr) << 1 z,c 2 fmulsu rd, rr fractional multiply signed with unsigned r1:r0 (rd x rr) << 1 z,c 2 branch instructions rjmp k relative jump pc pc + k + 1 none 2 ijmp indirect jump to (z) pc z none 2 rcall k relative subroutine call pc pc + k + 1 none 3 icall indirect call to (z) pc znone3 ret subroutine return pc stack none 4 reti interrupt return pc stack i 4 cpse rd,rr compare, skip if equal if (rd = rr) pc pc + 2 or 3 none 1 / 2 / 3 cp rd,rr compare rd ? rr z, n,v,c,h 1 cpc rd,rr compare with carry rd ? rr ? c z, n,v,c,h 1 cpi rd,k compare register with immediate rd ? k z, n,v,c,h 1 sbrc rr, b skip if bit in register cleared if (rr(b)=0) pc pc + 2 or 3 none 1 / 2 / 3 sbrs rr, b skip if bit in register is set if (rr(b)=1) pc pc + 2 or 3 none 1 / 2 / 3 sbic p, b skip if bit in i/o register cleared if (p(b)=0) pc pc + 2 or 3 none 1 / 2 / 3 sbis p, b skip if bit in i/o register is set if (p(b)=1) pc pc + 2 or 3 none 1 / 2 / 3 brbs s, k branch if status flag set if (sreg(s) = 1) then pc pc+k + 1 none 1 / 2 brbc s, k branch if status flag cleared if (sreg(s) = 0) then pc pc+k + 1 none 1 / 2 breq k branch if equal if (z = 1) then pc pc + k + 1 none 1 / 2 brne k branch if not equal if (z = 0) then pc pc + k + 1 none 1 / 2 brcs k branch if carry set if (c = 1) then pc pc + k + 1 none 1 / 2 brcc k branch if carry cleared if (c = 0) then pc pc + k + 1 none 1 / 2 brsh k branch if same or higher if (c = 0) then pc pc + k + 1 none 1 / 2 brlo k branch if lower if (c = 1) then pc pc + k + 1 none 1 / 2 brmi k branch if minus if (n = 1) then pc pc + k + 1 none 1 / 2 brpl k branch if plus if (n = 0) then pc pc + k + 1 none 1 / 2 brge k branch if greater or equal, signed if (n v= 0) then pc pc + k + 1 none 1 / 2 brlt k branch if less than zero, signed if (n v= 1) then pc pc + k + 1 none 1 / 2 brhs k branch if half carry flag set if (h = 1) then pc pc + k + 1 none 1 / 2 brhc k branch if half carry flag cleared if (h = 0) then pc pc + k + 1 none 1 / 2 brts k branch if t flag set if (t = 1) then pc pc + k + 1 none 1 / 2 brtc k branch if t flag cleared if (t = 0) then pc pc + k + 1 none 1 / 2 brvs k branch if overflow flag is set if (v = 1) then pc pc + k + 1 none 1 / 2 brvc k branch if overflow flag is cleared if (v = 0) then pc pc + k + 1 none 1 / 2 brie k branch if interrupt enabled if ( i = 1) then pc pc + k + 1 none 1 / 2 brid k branch if interrupt disabled if ( i = 0) then pc pc + k + 1 none 1 / 2 data transfer instructions
302 atmega8535(l) 2502k?avr?10/06 mov rd, rr move between registers rd rr none 1 movw rd, rr copy register word rd+1:rd rr+1:rr none 1 ldi rd, k load immediate rd knone1 ld rd, x load indirect rd (x) none 2 ld rd, x+ load indirect and post-inc. rd (x), x x + 1 none 2 ld rd, - x load indirect and pre-dec. x x - 1, rd (x) none 2 ld rd, y load indirect rd (y) none 2 ld rd, y+ load indirect and post-inc. rd (y), y y + 1 none 2 ld rd, - y load indirect and pre-dec. y y - 1, rd (y) none 2 ldd rd,y+q load indirect with displacement rd (y + q) none 2 ld rd, z load indirect rd (z) none 2 ld rd, z+ load indirect and post-inc. rd (z), z z+1 none 2 ld rd, -z load indirect and pre-dec. z z - 1, rd (z) none 2 ldd rd, z+q load indirect with displacement rd (z + q) none 2 lds rd, k load direct from sram rd (k) none 2 st x, rr store indirect (x) rr none 2 st x+, rr store indirect and post-inc. (x) rr, x x + 1 none 2 st - x, rr store indirect and pre-dec. x x - 1, (x) rr none 2 st y, rr store indirect (y) rr none 2 st y+, rr store indirect and post-inc. (y) rr, y y + 1 none 2 st - y, rr store indirect and pre-dec. y y - 1, (y) rr none 2 std y+q,rr store indirect with displacement (y + q) rr none 2 st z, rr store indirect (z) rr none 2 st z+, rr store indirect and post-inc. (z) rr, z z + 1 none 2 st -z, rr store indirect and pre-dec. z z - 1, (z) rr none 2 std z+q,rr store indirect with displacement (z + q) rr none 2 sts k, rr store direct to sram (k) rr none 2 lpm load program memory r0 (z) none 3 lpm rd, z load program memory rd (z) none 3 lpm rd, z+ load program memory and post-inc rd (z), z z+1 none 3 spm store program memory (z) r1:r0 none - in rd, p in port rd pnone1 out p, rr out port p rr none 1 push rr push register on stack stack rr none 2 pop rd pop register from stack rd stack none 2 bit and bit-test instructions sbi p,b set bit in i/o register i/o(p,b) 1none2 cbi p,b clear bit in i/o register i/o(p,b) 0none2 lsl rd logical shift left rd(n+1) rd(n), rd(0) 0 z,c,n,v 1 lsr rd logical shift right rd(n) rd(n+1), rd(7) 0 z,c,n,v 1 rol rd rotate left through carry rd(0) c,rd(n+1) rd(n),c rd(7) z,c,n,v 1 ror rd rotate right through carry rd(7) c,rd(n) rd(n+1),c rd(0) z,c,n,v 1 asr rd arithmetic shift right rd(n) rd(n+1), n=0..6 z,c,n,v 1 swap rd swap nibbles rd(3..0) rd(7..4),rd(7..4) rd(3..0) none 1 bset s flag set sreg(s) 1 sreg(s) 1 bclr s flag clear sreg(s) 0 sreg(s) 1 bst rr, b bit store from register to t t rr(b) t 1 bld rd, b bit load from t to register rd(b) tnone1 sec set carry c 1c1 clc clear carry c 0 c 1 sen set negative flag n 1n1 cln clear negative flag n 0 n 1 sez set zero flag z 1z1 clz clear ze ro flag z 0 z 1 sei global interrupt enable i 1i1 cli global interrupt disable i 0 i 1 ses set signed test flag s 1s1 cls clear signed test flag s 0 s 1 sev set twos complement overflow. v 1v1 clv clear twos complement overflow v 0 v 1 set set t in sreg t 1t1 clt clear t in sreg t 0 t 1 seh set half carry flag in sreg h 1h1 clh clear half carry flag in sreg h 0 h 1 mcu control instructions nop no operation none 1 mnemonics operands description operation flags #clocks
303 atmega8535(l) 2502k?avr?10/06 sleep sleep (see specific descr. for sleep function) none 1 wdr watchdog reset (see specific descr. for wdr/timer) none 1 break break for on-chip debug only none n/a mnemonics operands description operation flags #clocks
304 atmega8535(l) 2502k?avr?10/06 ordering information note: 1. this device can also be supplied in wafer form. please contact your local atmel sales office for detailed ordering infor mation and minimum quantities.. 2. pb-free packaging alternative, complies to the european dire ctive for restriction of hazardous substances (rohs direc- tive).also halide free and fully green. speed (mhz) power supply ordering code package (1) operation range 8 2.7 - 5.5v atmega8535l-8ac atmega8535l-8pc atmega8535l-8jc atmega8535l-8mc 44a 40p6 44j 44m1 commercial ( 0 c to 70 c) atmega8535l-8ai atmega8535l-8pi atmega8535l-8ji atmega8535l-8mi atmega8535l-8au (2) atmega8535l-8pu (2) atmega8535l-8ju (2) atmega8535l-8mu (2) 44a 40p6 44j 44m1 44a 40p6 44j 44m1 industrial (-4 0 c to 85 c) 16 4.5 - 5.5v atmega8535-16ac atmega8535-16pc atmega8535-16jc atmega8535-16mc 44a 40p6 44j 44m1 commercial ( 0 c to 70 c) atmega8535-16ai atmega8535-16pi atmega8535-16ji atmega8535-16mi atmega8535-16au (2) atmega8535-16pu (2) atmega8535-16ju (2) atmega8535-16mu (2) 44a 40p6 44j 44m1 44a 40p6 44j 44m1 industrial (-4 0 c to 85 c)
305 atmega8535(l) 2502k?avr?10/06 package type 44a 44-lead, thin (1.0 mm) plastic gull wing quad flat package (tqfp) 40p6 40-pin, 0.600? wide, plastic dual inline package (pdip) 44j 44-lead, plastic j-leaded chip carrier (plcc) 44m1-a 44-pad, 7 x 7 x 1.0 mm body, lead pitch 0.50 mm, quad flat no-lead/micro lead frame package (qfn/mlf)
306 atmega8535(l) 2502k?avr?10/06 packaging information 44a 2325 orchard parkway san jose, ca 95131 title drawing no. r rev. 44a, 44-lead, 10 x 10 mm body size, 1.0 mm body thickness, 0.8 mm lead pitch, thin profile plastic quad flat package (tqfp) b 44a 10/5/2001 pin 1 identifier 0?~7? pin 1 l c a1 a2 a d1 d e e1 e b common dimensions (unit of measure = mm) symbol min nom max note notes: 1. this package conforms to jedec reference ms-026, variation acb. 2. dimensions d1 and e1 do not include mold protrusion. allowable protrusion is 0.25 mm per side. dimensions d1 and e1 are maximum plastic body size dimensions including mold mismatch. 3. lead coplanarity is 0.10 mm maximum. a ? ? 1.20 a1 0.05 ? 0.15 a2 0.95 1.00 1.05 d 11.75 12.00 12.25 d1 9.90 10.00 10.10 note 2 e 11.75 12.00 12.25 e1 9.90 10.00 10.10 note 2 b 0.30 ? 0.45 c 0.09 ? 0.20 l 0.45 ? 0.75 e 0.80 typ
307 atmega8535(l) 2502k?avr?10/06 40p6 2325 orchard parkway san jose, ca 95131 title drawing no. r rev. 40p6 , 40-lead (0.600"/15.24 mm wide) plastic dual inline package (pdip) b 40p6 09/28/01 pin 1 e1 a1 b ref e b1 c l seating plane a 0o ~ 15o d e eb common dimensions (unit of measure = mm) symbol min nom max note a ? ? 4.826 a1 0.381 ? ? d 52.070 ? 52.578 note 2 e 15.240 ? 15.875 e1 13.462 ? 13.970 note 2 b 0.356 ? 0.559 b1 1.041 ? 1.651 l 3.048 ? 3.556 c 0.203 ? 0.381 eb 15.494 ? 17.526 e 2.540 typ notes: 1. this package conforms to jedec reference ms-011, variation ac. 2. dimensions d and e1 do not include mold flash or protrusion. mold flash or protrusion shall not exceed 0.25 mm (0.010").
308 atmega8535(l) 2502k?avr?10/06 44j notes: 1. this package conforms to jedec reference ms-018, variation ac. 2. dimensions d1 and e1 do not include mold protrusion. allowable protrusion is .010"(0.254 mm) per side. dimension d1 and e1 include mold mismatch and are measured at the extreme material condition at the upper or lower parting line. 3. lead coplanarity is 0.004" (0.102 mm) maximum. a 4.191 4.572 a1 2.286 3.048 a2 0.508 d 17.399 17.653 d1 16.510 16.662 note 2 e 17.399 17.653 e1 16.510 16.662 note 2 d2/e2 14.986 16.002 b 0.660 0.813 b1 0.330 0.533 e 1.270 typ common dimensions (unit of measure = mm) symbol min nom max note 1.14(0.045) x 45? pin no. 1 identifier 1.14(0.045) x 45? 0.51(0.020)max 0.318(0.0125) 0.191(0.0075) a2 45? max (3x) a a1 b1 d2/e2 b e e1 e d1 d 44j , 44-lead, plastic j-leaded chip carrier (plcc) b 44j 10/04/01 2325 orchard parkway san jose, ca 95131 title drawing no. r rev.
309 atmega8535(l) 2502k?avr?10/06 44m1-a 2 3 25 orch a rd p a rkw a y sa n jo s e, ca 951 3 1 title drawing no. r rev. 44m1 , 44-p a d, 7 x 7 x 1.0 mm body, le a d pitch 0.50 mm, g 44m1 5/27/06 common dimen s ion s (unit of me asu re = mm) s ymbol min nom max note a 0. 8 0 0.90 1.00 a1 ? 0.02 0.05 a 3 0.25 ref b 0.1 8 0.2 3 0. 3 0 d d2 5.00 5.20 5.40 6.90 7.00 7.10 6.90 7.00 7.10 e e2 5.00 5.20 5.40 e 0.50 b s c l 0.59 0.64 0.69 k 0.20 0.26 0.41 note: jedec s t a nd a rd mo-220, fig. 1 ( s aw s ing u l a tion) vkkd- 3 . top view s ide view bottom view d e m a rked pin# 1 id e2 d2 b e pin #1 corner l a1 a 3 a s eating plane pin #1 tr i a ngle pin #1 ch a mfer (c 0. 3 0) option a option b pin #1 notch (0.20 r) option c k k 1 2 3 5.20 mm expo s ed p a d, micro le a d fr a me p a ck a ge (mlf)
310 atmega8535(l) 2502k?avr?10/06 errata the revision letter refer to the device revision. atmega8535 rev. a and b ? first analog comparator conversion may be delayed ? asynchronous oscillator does not stop in power-down 1. first analog comparator conversion may be delayed if the device is powered by a slow rising v cc , the first analog comparator conver- sion will take longer than ex pected on some devices. problem fix/workaround when the device has been powered or reset, disable then enable the analog com- parator before the first conversion. 2. asynchronous oscillator does not stop in power-down the asynchronous oscillator does not stop when entering power-down mode. this leads to higher power consumption than expected. problem fix/workaround manually disable the asynchronous timer before entering power-down.
311 atmega8535(l) 2502k?avr?10/06 datasheet revision history please note that the referring page numbers in this section are referring to this docu- ment. the referring revision in this section are referring to the document revision. changes from rev. 2502j- 08/06 to rev. 2502k- 10/06 1. updated top/bottom description for all timer/counters fast pwm mode. 2. updated ?errata? on page 310. changes from rev. 2502i- 06/06 to rev. 2502j- 08/06 1. updated ?ordering information? on page 304. changes from rev. 2502h- 04/06 to rev. 2502i- 06/06 1. updated code example ?usart initialization? on page 150. changes from rev. 2502g- 04/05 to rev. 2502h- 04/06 1. added ?resources? on page 6. 2. updated table 7 on page 29, table 17 on page 42 and table 111 on page 258. 3. updated ?serial peripheral interface ? spi? on page 136. 4. updated note in ?bit rate generator unit? on page 180. changes from rev. 2502f- 06/04 to rev. 2502g- 04/05 1. removed ?preliminary? and tbd?s. 2. updated table 37 on page 69 and table 113 on page 261. 3. updated ?electrical characteristics? on page 255. 4. updated ?ordering information? on page 304. changes from rev. 2502e-12/03 to rev. 2502g-06/04 1. mlf-package alternative changed to ?quad flat no-lead/micro lead frame package qfn/mlf?. changes from rev. 2502e-12/03 to rev. 2502f-06/04 1. updated ?reset characteristics? on page 37. 2. updated sph in ?stack pointer? on page 12. 3. updated c code in ?usart initialization? on page 150. 4. updated ?errata? on page 310. changes from rev. 2502d-09/03 to rev. 2502e-12/03 1. updated ?calibrated internal rc oscillator? on page 29. 2. added section ?errata? on page 310.
312 atmega8535(l) 2502k?avr?10/06 changes from rev. 2502c-04/03 to rev. 2502d-09/03 1. removed ?advance information? and some tbd?s from the datasheet. 2. added note to ?pinout atmega8535? on page 2. 3. updated ?reset characteristics? on page 37. 4. updated ?absolute maximum ratings? and ?dc characteristics? in ?electrical characteristics? on page 255. 5. updated table 111 on page 258. 6. updated ?adc characteristics? on page 263. 7. updated ?atmega8535 typical characteristics? on page 266. 8. removed call and jmp instructions from code examples and ?instruction set summary? on page 301. changes from rev. 2502b-09/02 to rev. 2502c-04/03 1. updated ?packaging information? on page 306. 2. updated figure 1 on page 2, figure 84 on page 179, figure 85 on page 185, figure 87 on page 191, figure 98 on page 207. 3. added the section ?eeprom write du ring power-down sl eep mode? on page 22. 4. removed the references to the application notes ?multi-purpose oscillator? and ?32 khz crystal oscillator?, which do not exist. 5. updated code examples on page 44. 6. removed adhsm bit. 7. renamed port d pin icp to icp1. see ?alternate functions of port d? on page 64. 8. added information about pwm symmetry for timer 0 on page 79 and timer 2 on page 126. 9. updated table 68 on page 169, table 75 on page 190, table 76 on page 193, table 77 on page 196, table 108 on page 253, table 113 on page 261. 10. updated description on ?bit 5 ? twsta: twi start condition bit? on page 182. 11. updated the description in ?filling the temporary buffer (page loading)? and ?performing a page write? on page 231. 12. removed the section description in ?spi serial programming characteristics? on page 254. 13. updated ?electrical characteristics? on page 255.
313 atmega8535(l) 2502k?avr?10/06 14. updated ?adc characteristics? on page 263. 14. updated ?register summary? on page 299. 15. various timer 1 corrections. 16. added wd_fuse period in table 108 on page 253. changes from rev. 2502a-06/02 to rev. 2502b-09/02 1. canged the endurance on the flash to 10,000 write/erase cycles.
314 atmega8535(l) 2502k?avr?10/06
i atmega8535(l) 2502k?avr?10/06 table of contents features............... .............. .............. ............... .............. .............. .......... 1 pin configurations............ .............. ............... .............. .............. .......... 2 disclaimer ............................................................................................................. 2 overview.............. .............. .............. ............... .............. .............. .......... 3 block diagram ...................................................................................................... 3 at90s8535 compatibility ..................................................................................... 4 pin descriptions.................................................................................................... 5 resources ........... .............. .............. ............... .............. .............. .......... 6 about code examples........... ................ ................. ................ ............. 7 avr cpu core ................ ................ ............... .............. .............. .......... 8 introduction ........................................................................................................... 8 architectural overview.......................................................................................... 8 alu ? arithmetic logic unit.................................................................................. 9 status register ................................................................................................... 10 general purpose register file ........................................................................... 11 stack pointer ...................................................................................................... 12 instruction execution timing............................................................................... 13 reset and interrupt handling.............................................................................. 13 avr atmega8535 memories ....... .............. .............. .............. ........... 16 in-system reprogrammable flash program memory ........................................ 16 sram data memory........................................................................................... 17 eeprom data memory............ ................ ................ ................ ................ .......... 18 i/o memory ......................................................................................................... 23 system clock and clock options ............. .............. .............. ........... 24 clock systems and their distribution .................................................................. 24 clock sources..................................................................................................... 25 default clock source .......................................................................................... 25 crystal oscillator................................................................................................. 25 low-frequency crystal oscillator ........................................................................ 28 external rc oscillator ........................................................................................ 28 calibrated internal rc oscillator .............. .......................................................... 29 external clock..................................................................................................... 31 timer/counter oscillator........................... .......................................................... 31 power management and sleep modes......... .............. .............. ........ 32 idle mode ............................................................................................................ 33 adc noise reduction mode............................................................................... 33 power-down mode.............................................................................................. 33 power-save mode............................................................................................... 33
ii atmega8535(l) 2502k?avr?10/06 standby mode..................................................................................................... 34 extended standby mode .................................................................................... 34 minimizing power consumption ......................................................................... 35 system control and reset ..... ............... ................. ................ ........... 36 internal voltage reference ................................................................................. 41 watchdog timer ................................................................................................. 41 timed sequences for changing the configuration of the watchdog timer ....... 45 interrupts ................ ................ ................ ................. ................ ........... 46 interrupt vectors in atmega8535....................................................................... 46 i/o-ports........ ................. ................ .............. .............. .............. ........... 51 introduction ......................................................................................................... 51 ports as general digital i/o ................................................................................ 52 alternate port functions ..................................................................................... 57 register description for i/o-ports....................................................................... 66 external interrupts.......... .............. .............. .............. .............. ........... 68 8-bit timer/counter0 with pw m............... ................ .............. ........... 71 overview............................................................................................................. 71 timer/counter clock sources............................................................................. 72 counter unit........................................................................................................ 72 output compare unit.......................................................................................... 73 compare match output unit ............................................................................... 75 modes of operation ............................................................................................ 76 timer/counter timing diagrams......................................................................... 80 8-bit timer/counter register description ........................................................... 83 timer/counter0 and timer/counter1 pr escalers ............. ............... 87 16-bit timer/counter1.......... ................ ................. ................ ............. 89 overview............................................................................................................. 89 accessing 16-bit registers ................................................................................. 92 timer/counter clock sources............................................................................. 95 counter unit........................................................................................................ 95 input capture unit............................................................................................... 96 output compare units ........................................................................................ 98 compare match output unit ............................................................................. 100 modes of operation .......................................................................................... 101 timer/counter timing diagrams....................................................................... 108 16-bit timer/counter register description ....................................................... 110 8-bit timer/counter2 with pw m and asynchronous operation .. 117
iii atmega8535(l) 2502k?avr?10/06 overview........................................................................................................... 117 timer/counter clock sources........................................................................... 118 counter unit...................................................................................................... 119 output compare unit........................................................................................ 119 compare match output unit ............................................................................. 121 modes of operation .......................................................................................... 122 timer/counter timing diagrams....................................................................... 126 8-bit timer/counter register description ......................................................... 128 asynchronous operation of the timer/counter ................................................ 131 timer/counter prescaler................................................................................... 134 serial peripheral interface ? spi................ .............. .............. ......... 136 ss pin functionality.......................................................................................... 141 data modes ...................................................................................................... 144 usart ............... .............. .............. .............. .............. .............. ......... 145 overview........................................................................................................... 145 clock generation .............................................................................................. 146 frame formats ................................................................................................. 149 usart initialization.......................................................................................... 150 data transmission ? the usart transmitter ................................................. 152 data reception ? the usart receiver .......................................................... 155 asynchronous data reception ......................................................................... 158 multi-processor communication mode ............................................................. 162 accessing ubrrh/ucsrc registers.............................................................. 163 usart register description ............................................................................ 164 examples of baud rate setting........................................................................ 170 two-wire serial interface .... ................ ................. ................ ........... 174 features............................................................................................................ 174 two-wire serial interface bus definition........................................................... 174 data transfer and frame format ..................................................................... 175 multi-master bus systems, arbitration and synchronization ............................ 177 overview of the twi module ............................................................................ 179 twi register description.................................................................................. 181 using the twi ................................................................................................... 185 transmission modes......................................................................................... 188 multi-master systems and arbitration............................................................... 201 analog comparator ............. ................ ................. ................ ........... 203 analog comparator multiplexed input .............................................................. 205 analog-to-digital converter. ............... ................. ................ ........... 206 features............................................................................................................ 206 operation .......................................................................................................... 207 starting a conversion ....................................................................................... 208
iv atmega8535(l) 2502k?avr?10/06 prescaling and conversion timing ................................................................... 209 changing channel or reference selection ...................................................... 212 adc noise canceler......................................................................................... 214 adc conversion result.................................................................................... 218 boot loader support ? read-while- write self-programming ..... 224 boot loader features ....................................................................................... 224 application and boot loader flash sections .................................................... 224 read-while-write and no read-while-write flash sections........................... 224 boot loader lock bits....................................................................................... 226 entering the boot loader program ................................................................... 227 addressing the flash during self-programming ............................................... 229 self-programming the flash ............................................................................. 230 memory programming........... ................ ................. ................ ......... 237 program and data memory lock bits .............................................................. 237 fuse bits........................................................................................................... 238 signature bytes ................................................................................................ 239 calibration byte ................................................................................................ 239 parallel programming parameters, pin mapping, and commands .................. 240 parallel programming ....................................................................................... 242 serial downloading........................................................................................... 251 electrical characteristics...... ................ ................. ................ ......... 255 absolute maximum ratings*............................................................................. 255 dc characteristics............................................................................................ 255 external clock drive waveforms ...................................................................... 258 external clock drive ......................................................................................... 258 two-wire serial interface characteristics ......................................................... 259 spi timing characteristics ............................................................................... 261 adc characteristics ......................................................................................... 263 atmega8535 typical characteris tics .............. ............ ............ ...... 266 register summary ..... ................. ................ .............. .............. ......... 299 instruction set summary ...... ................ ................. ................ ......... 301 ordering information........... ................ ................. ................ ........... 304 packaging information .......... ................ ................. ................ ......... 306 44a ................................................................................................................... 306 40p6 ................................................................................................................. 307 44j .................................................................................................................... 308 44m1-a ............................................................................................................. 309
v atmega8535(l) 2502k?avr?10/06 errata ............... ................ .............. .............. .............. .............. ......... 310 atmega8535 rev. a and b..................................................................................................... 310 datasheet revision history ... ............... ................. ................ ......... 311 changes from rev. 2502j- 08/06 to rev. 2502k- 10/06.................................. 311 changes from rev. 2502i- 06/06 to rev. 2502j- 08/06 ................................... 311 changes from rev. 2502h- 04/06 to rev. 2502i- 06/06 .................................. 311 changes from rev. 2502g- 04/05 to rev. 2502h- 04/06................................. 311 changes from rev. 2502f- 06/04 to rev. 2502g- 04/05 ................................. 311 changes from rev. 2502e-12/03 to rev. 2502g-06/04................................... 311 changes from rev. 2502e-12/03 to rev. 2502f-06/04 ................................... 311 changes from rev. 2502d-09/03 to rev. 2502e-12/03 ................................... 311 changes from rev. 2502c-04/03 to rev. 2502d-09/03................................... 312 changes from rev. 2502b-09/02 to rev. 2502c-04/03 ................................... 312 changes from rev. 2502a-06/02 to rev. 2502b-09/02 ................................... 313 table of contents ................ .............. .............. .............. .............. ......... i
vi atmega8535(l) 2502k?avr?10/06
2502k?avr?10/06 disclaimer: the information in this document is provided in connection with atmel products. no license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this document or in connection with the sale of atmel products. except as set forth in atmel?s terms and condi- tions of sale located on atmel? s web site, atmel assumes no liability whatsoever and disclaims any express, implied or statutor y warranty relating to its products including, but not limited to , the implied warranty of merchantability, fitness for a particu lar purpose, or non-infringement. in no event shall atmel be liable for any direct, indirect, conseque ntial, punitive, special or i nciden- tal damages (including, without limitation, damages for loss of profits, business interruption, or loss of information) arising out of the use or inability to use this document, even if at mel has been advised of the possibility of such damages. atmel makes no representations or warranties with respect to the accuracy or co mpleteness of the contents of this document and reserves the rig ht to make changes to specifications and product descriptions at any time without notice. atmel does not make any commitment to update the information contained her ein. atmel?s products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life. atmel corporation atmel operations 2325 orchard parkway san jose, ca 95131, usa tel: 1(408) 441-0311 fax: 1(408) 487-2600 regional headquarters europe atmel sarl route des arsenaux 41 case postale 80 ch-1705 fribourg switzerland tel: (41) 26-426-5555 fax: (41) 26-426-5500 asia room 1219 chinachem golden plaza 77 mody road tsimshatsui east kowloon hong kong tel: (852) 2721-9778 fax: (852) 2722-1369 japan 9f, tonetsu shinkawa bldg. 1-24-8 shinkawa chuo-ku, tokyo 104-0033 japan tel: (81) 3-3523-3551 fax: (81) 3-3523-7581 memory 2325 orchard parkway san jose, ca 95131, usa tel: 1(408) 441-0311 fax: 1(408) 436-4314 microcontrollers 2325 orchard parkway san jose, ca 95131, usa tel: 1(408) 441-0311 fax: 1(408) 436-4314 la chantrerie bp 70602 44306 nantes cedex 3, france tel: (33) 2-40-18-18-18 fax: (33) 2-40-18-19-60 asic/assp/smart cards zone industrielle 13106 rousset cedex, france tel: (33) 4-42-53-60-00 fax: (33) 4-42-53-60-01 1150 east cheyenne mtn. blvd. colorado springs, co 80906, usa tel: 1(719) 576-3300 fax: 1(719) 540-1759 scottish enterprise technology park maxwell building east kilbride g75 0qr, scotland tel: (44) 1355-803-000 fax: (44) 1355-242-743 rf/automotive theresienstrasse 2 postfach 3535 74025 heilbronn, germany tel: (49) 71-31-67-0 fax: (49) 71-31-67-2340 1150 east cheyenne mtn. blvd. colorado springs, co 80906, usa tel: 1(719) 576-3300 fax: 1(719) 540-1759 biometrics/imagin g/hi-rel mpu/ high speed converters/rf datacom avenue de rochepleine bp 123 38521 saint-egreve cedex, france tel: (33) 4-76-58-30-00 fax: (33) 4-76-58-34-80 literature requests www.atmel.com/literature ? 2006 atmel corporation . all rights reserved. atmel ? , logo and combinations thereof, everywhere you are ? , avr ? , and others are the trade- marks or registered trademarks of atmel corporation or its subs idiaries. other terms and product names may be trademarks of oth ers.


▲Up To Search▲   

 
Price & Availability of ATMEGA8535L-8AUR

All Rights Reserved © IC-ON-LINE 2003 - 2022  

[Add Bookmark] [Contact Us] [Link exchange] [Privacy policy]
Mirror Sites :  [www.datasheet.hk]   [www.maxim4u.com]  [www.ic-on-line.cn] [www.ic-on-line.com] [www.ic-on-line.net] [www.alldatasheet.com.cn] [www.gdcy.com]  [www.gdcy.net]


 . . . . .
  We use cookies to deliver the best possible web experience and assist with our advertising efforts. By continuing to use this site, you consent to the use of cookies. For more information on cookies, please take a look at our Privacy Policy. X